Mongoose:如何查询引用的对象属性? [英] Mongoose: How to query for a referenced object property?

查看:561
本文介绍了Mongoose:如何查询引用的对象属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从一个子文档的属性中获取我的数据库中的文档列表。我使用的模型和模式是:

I'm trying to get a list of documents from my database based on the property a sub-document. The models and schemas I'm using are:

var elementSchema = new mongoose.Schema({
    name: String,
    description: String,

    _story: { type: mongoose.Schema.Types.ObjectId, ref: 'Story' },

    date_created: Date,
    date_modified: Date,
};
var storySchema = new mongoose.Schema({
    title: {type: String, default: '', trim: true},
    isPrivate: {type: Boolean, default: false},
});

mongoose.model("Story", storySchema);
mongoose.model("Element", elementSchema);

我试图获取属于故事不是私有的所有元素,根据我在这里看到的一些帖子( 1 2 3 )解决方案是使用_story.isPrivate与find。我正在这样做:

I'm trying to get all Elements that belong to a Story that is not private, and according to some posts I saw around here (1, 2, 3) the solution would be to use _story.isPrivate with find. I'm currently doing this:

Element.find({'_story.isPrivate': false})
         .populate('_story')
         .exec(function(err, elements){
             if(err){
                 return next(err);
             }
             else if(elements.length > 0){
                 return res.send(elements);
             }
             else{
                 return res.send(404, {message: "No elements found"});
             }
});

但结果总是一个空集(返回404)。没有条件,find返回所有元素并正确填充_story。我还激活了调试输出以查看正在执行的查询,我得到这个:

But the result is always an empty set (returns 404). With no condition, find returns all elements and populates _story correctly. I also activated the debug output to see the queries being executed and I get this:

Mongoose: elements.find({ '_story.isPrivate': false }) { fields: undefined, safe: undefined }

尝试执行此操作MongoDB我没有结果。这里有什么问题?

Trying to execute this in MongoDB I get no results. What can be wrong here?

谢谢

推荐答案

JohnnyHK。他说实话Mongodb查询一次只能使用一个数据,只能使用一个数据。由于元素集合中的文档没有一个 _story.isPrivate 键路径, Element.find({'_ story.isPrivate': false})将永远不会匹配任何文档。 mongodb没有加入。真。然而,鉴于否连接约束,仍然可以构建应用程序并满足用例,但是您需要替代模式和查询设计。有时候,人们会对他们的数据进行非规范化处理并重复。有时您运行多个相关查询等等。

Listen to @JohnnyHK. He speaks the truth. Mongodb queries use the data in one and only one and exactly one collection at a time. Since documents in the 'elements' collection don't ever have a _story.isPrivate key path, Element.find({'_story.isPrivate': false}) will never match any document. There are no joins in mongodb. Really. However, given the "no joins" constraint, it is still possible to build an application and meet use cases, but you need alternative schemas and query designs. Sometimes people denormalize their data and duplicate stuff. Sometimes you run multiple related queries, etc, etc.

这篇关于Mongoose:如何查询引用的对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆