In this tutorial, we are learning that the mongoose joins two collections with the 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 replaces (updates) the specified path (schema ID) in the document, with a document of a different model.
Mongoose Join two collections Create schema
We will make Schema a user and another post as you can 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 both created Schema and matched the object_id. This user and post schema, the user schema property called Post schema that refers to an array for Post'id, and the post schema called User Schema refers to the identification of a user.
Then Saving References to Other Documents works the same way it normally saves properties, just set the id value:
try {
const user = User.create({
name:"Robert Look",
email: "gajanand.kgn@gmail.com"
})
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)
}
});
I hope it can help you...