Easy Way
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. more Help
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);
//----------
User.findOne({
name: "Robert Look"
}).populate('posts').exec((err, user) =>{
if(err){
console.log(err)
}else{
console.log(users.posts[0].desc)
}
});