Search code examples
node.jsmongoosemongoose-populate

How to use moongoose populate?


I have two schemas one book and other user

 let mongoose = require('mongoose'),
        Schema = mongoose.Schema;

    let book = new Schema({
        id: {type : Schema.Types.ObjectId, default: null},
        author: {type : Array, default: []},
        userId:{type:Array,default:[]},
        issued:[{type:Schema.Types.ObjectId,ref:'users'}]
    });

    let user = new Schema({
       id: {type : Schema.Types.ObjectId, default: null},
       name:{type : String, default: null},
       address:{type : String, default: null}
    });

Issued property in book schema carries the detail for the user who issued book.

Issued Property can be populated by using userId of book Schema and matching userId of book schema with an Id of user Schema.

let user =  mongoose.model("Model", userSchema, "users");
let book = mongoose.model("book", bookSchema);

  book.find({}).populate('users').exec(function (err, result) {
        console.log(result);
           //Query is failing what wrong i am doing.
    });

I am not able to determine how can I fetch user detail.

I want object like:

{  
    id: 8888998898989,
    author: 'Author ',
    userId:['232323232332','ssssssss'],
    issued:[
             {'id':232323232332,'name':'User1'},
             {'id':ssssssss,'name':'User2'}
            ]
  }

Solution

  • .populate({ path: 'userId', model: 'users', select:'id name address' })