How to place list of objects in MongoDB-Express app


With mongoose we can easily place list of objects and populate documents/objects in MongoDB.

The Modal objects

In the modal object of Post we can define a field for user which is another modal in our project.

The User Schema and ‘post’ list field

const mongoose = require('mongoose');
 const UserSchema = new mongoose.Schema({
     name :{
         type:String,
         required: '{PATH} is required!'
     }, 
     posts : [
         {type: mongoose.Schema.Types.ObjectId,ref:'Post'}
     ]    
 ,{
     timestamps: true
 })
 module.exports = mongoose.model('User',UserSchema);

The Post Schema

const mongoose = require('mongoose');
 const PostSchema = new mongoose.Schema({
     title: {
         type: String,
         required:   '{PATH} is required!'
     },
     content: {
         type: String,
         required:   '{PATH} is required!'
     },
 }, {
     timestamps: true
 })
 module.exports = mongoose.model('Post', PostSchema);

In the user we had defined a field posts (list ), which is intended to store the user posts object ( MongoDB object ID), which can be used for populating the post later.

In the express route method we have the postsByUser which fetch the user post in the user documents

 postsByUser: async (req, res) => {
        try {
           const {  id  } = req.params;
        console.log('User:'+id);
        const user = await User.findById(id).populate('posts');
        console.log('User ->' + user);
        res.send(user.posts);
         } catch(e) {
             // statements
             console.log(e);
             res.sta(401).send({error:e})
         } 
    }

The the route is called in the following manner

http://localhost:3005/user/find/post/5fe4ab1e69b8d525c44ec293

and the user posts will be shown as following

{
      "posts": [
        {
            "comments": [],
            "tags": [],
            "_id": "5fedcb477563625708ca7429",
            "title": "Welcome to react",
            "content": "A hello world Reactjs app",
            "user": "5fe4ab1e69b8d525c44ec293",
            "createdAt": "2020-12-31T12:59:51.559Z",
            "updatedAt": "2020-12-31T12:59:51.559Z",
            "__v": 0
        },
        {
            "comments": [],
            "tags": [],
            "_id": "5fedcbe67563625708ca742a",
            "title": "Helo",
            "content": "Hello word app",
            "user": "5fe4ab1e69b8d525c44ec293",
            "createdAt": "2020-12-31T13:02:30.724Z",
            "updatedAt": "2020-12-31T13:02:30.724Z",
            "__v": 0
        },   
}          

That’s it. Following mongoose posts deserve your attention

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.