Search code examples
node.jsmongoosemongoose-populate

populate in nodejs and mongoose not worked


i have a Schema for save info , in this info i have a userId and i want to return info of that Schema and return info of user form user Schema .

TravelRequestSchema :

 const TravelRequestSchema = new Schema({
    userId: { type: Schema.Types.ObjectId, ref: "User" }
    description: { type: String, require: true }
}, {
    toObject: { virtuals: true },
    toJSON: { virtuals: true }
});

User Schema :

 const UserSchema = new Schema({
    firstName: { type: String },
    lastName: { type: String },
    phoneNumber: { type: String },
    email: { type: String, defult: null }
},{
        toJSON: { virtuals: true }
});

now i write this quesy for get info :

await TravelRequestModel.find({})
        .populate('User')
        .exec();

but it not return the user info for me , it just return the UserId .

now how can i sovle this problem ??


Solution

  • You want your query to populate specific fields, not model names

    await TravelRequestModel.find({})
            .populate('userId')
            .exec();
    

    This is because if you had multiple fields that reference the same model, you want to be able to pick and choose which fields to populate.