0

I have a User model with a schema that I would like to validate an array of multiple friends by their id's. The portion of the schema that is supposed to do this is:

friends: {
    type: [mongoose.SchemaTypes.ObjectId],
},

Then, when I try to add a friend with an id value and populate it inside the API endpoint, it adds the id to the database, but does not populate it. Here is the code:

    if (method === "POST") {
        const userId = getIdFromCookie(req);
        try {
            const newFriend = {
                friends: req.body.friend
            };
            const updatedUser = await User.findByIdAndUpdate(userId, newFriend, {new: true})
            const popUser = await User.findById(userId).populate("friends")
            res.status(200).json({success: true, data: updatedUser});
        } catch (error) {
            res.status(400).json({success: false});
        }
    } else {
        res.status(400).json({error: "This endpoint only supports method 'POST'"})
    }

I want to know how I can add a friend's id to the database, whilst simultaneously populating it in the same endpoint.

  • Which mongoose version are you using? If it is monoose:5.x.x then you must use .lean() for more check this https://mongoosejs.com/docs/5.x/docs/api.html#model_Model.populate – Rakesh Jan 07 '23 at 03:36

1 Answers1

0

The user schema is missing the ref field.

Example from the docs:

stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]

Without the ref, Mongoose doesn't know where to lookup the ObjectId.

Joe
  • 25,000
  • 3
  • 22
  • 44