简体   繁体   中英

Query Pointer Array Mongoose Node.js

I have a normal MongoDB with 2 Collections:

A post with an Array of group pointer.

var Post = mongoose.model('Post', new mongoose.Schema({
    groups: {type: [{type: mongoose.Schema.Types.ObjectId, ref: 'Group'}]},
}));

var Group = mongoose.model('Group', new mongoose.Schema({
}));

Now I want to query all post which have a group given by a id in there groups array?

I tried the following:

return Post.find({ groups: req.body.groupId} },function(err,post){
    console.log(post);
    res.send(post);
});

I also tried to query first the group object und passing this instead of the groupId? Does anybody have an idea?

I think you have error in your Post schema, it should look like this:

   var Post = mongoose.model('Post', new mongoose.Schema({
        groups: [{type: mongoose.Schema.Types.ObjectId, ref: 'Group'}],
   }));

then your query should work correctly.

In addition to the correction by Yelizaveta, you left off mention of .populate(aaa) as in

return Post.find({ groups: req.body.groupId} },function(err,post){
    console.log(post);
    res.send(post);
}).populate('groups');

where you list the fields of type: Reference ... without this .populate() these fields will just list the ObjectId values, not the underlying document in the referenced other collection : group

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