How to populate selected fields in a mongo document path in expressjs


In Express-Nodejs app we are using mongoose driver for MongoDB, a NoSql database with speed and accuracy. Mongo store data as series of JSON element call document and the collection of document is called a collection , same as table in DBMS.

According to the Mongoose doc Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s)

So we have the following Document , in which we want to populate user information

[
    {
        "_id": "5fef1f5087a69346300003a7",
        "title": "Title post",
        "content": "It is a good practice to keep styles for different pages  in separate style sheets. Larger project this becomes more applicable. What you do when need to combine them in another ?",
        "user": "5fe4ab1e69b8d525c44ec293",
        "createdAt": "2021-01-01T13:10:40.468Z",
        "updatedAt": "2021-01-03T02:37:55.982Z",
        "__v": 11
    }
]

So the posts is a list of objects which should populate and inside each post have a user object as well. Our task is to primarily populate the specific user object fields.

We can do this right now using the find method of modal class accompanied by the populate command which specify the path and fields to populate as follows, also used a callback function.

const tid = req.params['tid']
			Tag.findById(tid).populate({
				path: 'posts',
				populate: {
					path: 'user',select:'name'
				}
			}).exec((err, post) => {
				if (err) return handleError(err)
				 
				return res.status(200).send(post.posts)


and the response will be as follows

[
    {
        "_id": "5fef1f5087a69346300003a7",
        "title": "Title post",
        "content": "It is a good practice to keep styles for different pages  in separate style sheets. Larger project this becomes more applicable. What you do when need to combine them in another ?",
        "user": {
            "password": "123",
            "posts": [
                "5feebf2b7e30080468ccd4c1",
                "5feec08a7e30080468ccd4c9",
                ]
            "_id": "5fe4ab1e69b8d525c44ec293",
            "name": "admin",             
        },
        "createdAt": "2021-01-01T13:10:40.468Z",
        "updatedAt": "2021-01-03T02:37:55.982Z",
        "__v": 11
    }
]

In the above code we had used the populate inside another populate because the each posts had user element.

We can use populate inside another one , find out how ? Next post will be on that !

Following mongoose post also deserve a good read

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.