简体   繁体   中英

Mongoose query populate match id of find elements

I'm trying to populate a model with data from another model. Those two models looks like this:

var postSchema = mongoose.Schema({
    _comments: { type: mongoose.Schema.Types.ObjectId, ref: 'Comment' },
    type: String,
    body: String,
});

var commentSchema = mongoose.Schema({
    id_post: mongoose.Schema.Types.ObjectId,
    body: String,
});

I want to find all posts and populate them with comments that have id_post == _id from founded Posts. Something like this:

Post.find({}).populate({
    path: '_comments',
    select: 'body',
    match: { post_id: Post._id }
    options: { limit: 5 }
})
.exec(function (err, posts){...});

First of all, There are few problems in the code you wrote. If each post may have many comments you should implement one-to-many relationship between your schemas, you can do it by surrounding the comment ref with []

var postSchema = mongoose.Schema({
    _comments:  [ {type: mongoose.Schema.Types.ObjectId, ref: 'Comment'} ] ,
    type: String,
    body: String,
});

id_post is not just a field of type ObjectId, it should be written like this:

var commentSchema = mongoose.Schema({
post: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' },
body: String,
});

When saving a new comment make sure you connect it to its post:

var comment = new Comment({
    body: "Hello",
    post: post._id    // assign the _id from the post
  }); 

comment.save(function (err) {
    if (err) return handleError(err);
    // thats it!
  });

Now when you want to find a post and populate its comments you should write something like this:

Post
.find(...)
.populate({
  path: '_comments',
  select: 'body',
  options: { limit: 5 }
})
.exec()

The reason I dropped the match is that match should be used when you want to filter according to a specific field, in your case you can use match to get only comments with type='something'.

populate should work because when you inserted the comment you made the bond to its post.

More information on the right way of using populate can be found here - Mongoose Query Population

Post data should be persisted the following way:

{
   body: "some body",
   type: "some type",
   _comments: [12346789, 234567890, ...]
}

More information about the way the ref will be persisted here - One-to-Many Relationships with Document References

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM