how do i add more fields in mongoose schema to a field which is an array of objects and these objects are referenced to another mongoose schema?

Because you have to specify the fields you want to populate.

User.findById(req.user._id).populate("viewed_posts", "hits actualViewsByUser", Post) // pass in the Post model as well (you'll have to import this).

I pass in the model as I’ve had errors before because Mongoose didn’t populate the fields for me correctly.

However, I’m not sure your approach is the best one. “hits” and “actualViewsByUser” would refer to a specific post via an ID. When you use populate Mongoose will take the id, look for the relevant post, then populate with the appropriate information “hits”, “actualViewsByUser”, etc. The “hits” and “actualViewsByUser” would need to be stored on your Post model, not your User model.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top