Use Object id to set relationship in MongoDB-Express app


Unlike relational database NoSql (MongoDB) don’t have relation between documents. Even though we can set relation by placing sub document inside one document using the Object id, which is generated by the 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

const mongoose = require('mongoose');
 const UserSchema = new mongoose.Schema({
     name :{
         type:String,
         required: '{PATH} is required!'
     },     
 ,{
     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!'
     },
  user: {     type: mongoose.Schema.Types.ObjectId,     ref: 'User' }
 }, {
     timestamps: true
 })
 module.exports = mongoose.model('Post', PostSchema);

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

In the express route method we have the following

const Post = require('../../models/post');
 const User = require('../../models/user');
 module.exports = {
     create: async (req, res) => {
 try {
      console.log(req.params);
         user = req.params;
         id = user.id;
         const {
             title,
             content,
         } = req.body;
         const post = await Post.create({
             title,
             content,
             user: id
         });
         await post.save();   

In the constructor , passed the user Object ID to the user field. The resulted MongoDB doc look like the following

New Post:{                                                                                                                      
   _id: 5fee99c33cbe8b25d0ced080,                                                                                                
   title: 'Happy New Year',                                                                                                      
   content: 'Happy New Year MEssage',                                                                                            
   user: 5fe4ab1e69b8d525c44ec293,                                                                                               
   createdAt: 2021-01-01T03:40:51.340Z,                                                                                          
   updatedAt: 2021-01-01T03:40:51.340Z,                                                                                          
   __v: 0                                                                                                                        
 }                

So How can we use the user objectID ?

Using the populate command we can get the complete User information as follows

Post.findById(post._id).populate('user').exec(function(error, post) {
                 console.log('New post - > ' + post);
             })

and the resulted document will be

{
        "_id": "5fe6ca34443a4d0f54aafece",
        "title": "Flutter apps",
        "content": "We are conducting a free workshop on Flutter",
        "user": {           
            "_id": "5fe4db85a4896d069006601b",
            "name": "emma",
            "createdAt": "2020-12-24T18:18:45.224Z",
            "updatedAt": "2020-12-24T18:20:47.857Z",
            "__v": 1
        },

That’s it. Following MongoDB 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.