2

I am trying to attach the full user model to each comment in my comments section. Since mongodb doesn't have joins I have been trying to figure out how to use .populate() to add the user object from the controller. As I understand it, to use the populate function there are only two things you must do.

  1. Define a ref in the model.
  2. Call .populate() on the name of the field which has a ref defined.

I have defined the ref in the model to the 'User' model:

var commentSchema = new mongoose.Schema({
  author: { type: String, ref: 'User' },
  description: String,
  commentID: String,
  hasParent: String,
  parentComment: String,
  timestamp: { type: Number, default: 0 },
});

Then I am trying to add the user model to the author field in the comment object:

Comment
  .find() 
  .populate('author')
  .exec(function (err, comments) {
    console.log(comments);
  }); 

Is there a step that I am missing? I was hoping to see all the comments with the full user object in the author field of each comment.

1
  • 1
    Your populate() does not seem to be the problem. I don't knwo about the structure of your User model, but you should reference the _id of the User. author: {type: Schema.ObjectId, ref:'User'} Commented Nov 12, 2014 at 8:18

2 Answers 2

2

The solution was deleting the comments collection from mongodb. Starting fresh it works as expected. If anyone runs into a similar problem try deleting the collection of objects that were created before you had added a ref to the model.

Sign up to request clarification or add additional context in comments.

Comments

0

Please consider making following changes.

author: { type: String, ref: 'User' };
authot: { type: Schema.Types.ObjectId, ref:'User'};

1 Comment

Did you mean authot? Code only answers can almost always be improved by adding some explanation of how and why they work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.