简体   繁体   English

查询指针数组猫鼬Node.js

[英]Query Pointer Array Mongoose Node.js

I have a normal MongoDB with 2 Collections: 我有2个集合的普通MongoDB:

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? 现在,我要查询所有具有在groups数组中由id给出的组的帖子?

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? 我也尝试过先查询组对象und通过此对象而不是groupId? Does anybody have an idea? 有人有主意吗?

I think you have error in your Post schema, it should look like this: 我认为您的Post模式中有错误,它应该看起来像这样:

   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 除了Yelizaveta的更正外,您还没有提到.populate(aaa),

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 您在其中列出类型的字段的地方:Reference ... ...如果没有此.populate(),这些字段将仅列出ObjectId值,而不列出所引用的其他collection中的基础文档:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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