Joining Two Collections In A Mongoose With Example


In this tutorial, we are learning mongoose join two collections with example. As we saw earlier in MySQL, how we join tables, we will join the collection in mongoose, we will see below.

In mongoose, the alternative is called populate(). This process automatically replacing (update) the specified path  (schema Id) in the document, with a document from a different model.

Joining Two Collections In A Mongoose With Example

We have already installed Mongoose in Node.js and are creating APIs with the help of the Express framework. You can do any other work like building a website.

Blender - How To Join Objects Toget...
Blender - How To Join Objects Together

Mongoose Join Two Collections Create Schema

We will make Schema a user and another post as you see below

const { Schema, model} = require("mongoose");

const UserSchema = new Schema({
   name:{
      type: String,
      required: true
   },
   email:{
      type: String,
      required: true
   },
   posts:[{
      type: Schema.Types.ObjectId, ref: "Post"
   }]
});


const PostSchema = new Schema({
   title: String,
   desc: String,
   User: {type: Schema.Tpes.ObjectId, ref: "User"}
});

export const Post = model("Post", PostSchema);
export const User = model("User", UserSchema);

Above we saw how we two make Schema and match the object_id. This Schema Users and posts, User's Schema property called a posts Schema that references an array for Post'id and Post's Schema called user Schema reference a User's id.

Then, Saving references to other documents works the same way you normally save properties, just assign the _id value:

try {
   const user = User.create({
      name:"Robert Look",
      email: "[email protected]"
   })

   try {
      const post1 = Post.create({
         title: "This is a first post",
         desc: "this a a first description"
         user: User._id // assign the _id from the user
      });
   } catch (err) {
      console.log(err.message)
   }
} catch (err) {
   console.log(err.message)
}

Reading Models

Now that our tables reference one another, let’s take a look at populating our post’s user using the populate() query builder:

User.findOne({
   name: "Robert Look"
}).populate('posts').exec((err, user) =>{
   if(err){
      console.log(err)
   }else{
      console.log(users.posts[0].desc)
   }
});

Conclusion

We saw above how to use populate We also saw how joining two documents in mongoose (MongoDB), if you write the query correctly then you will get a good result or your JSON.


I hope it can help you...

Leave a Reply

Your privacy will not be published. Required fields are marked *

We'll share your Website Only Trusted.!!

close