Search code examples
javascriptnode.jsexpressmongoosemongoose-populate

mongoose multiple reference to single field and populate same type of two fields together


 const Schema = mongoose.Schema;
 
 const userSchema = Schema({
     helper_member: { type: Schema.Types.ObjectId, ref: 'onModel'},
     sponser_member: { type: Schema.Types.ObjectId, ref:'onModel'},
     onModel: {
       type: String,
       required:true,
       enum: ['user','admin']
     },
   
   });
   const User = mongoose.model('user', userSchema);
   module.exports = {User} ;
find().populate('sponser_member helper_member',{ _id:0,full_name: 1,user_name:1,designation:1,earnings:1})

I have tried this but no use

so how can I do this if I have multiple fields


Solution

  • Im not very sure what the problem is but try this:

    const result = await User.find({}).populate("helper_member sponser_member")
    

    This should find all users in the database and populte the fields by reference.

    Also make sure that the reference does actually exists.