Mongoose:如何查询引用的对象属性?
我试图从我的数据库中获取基于属性子文档的文档列表。 我使用的模型和模式是:
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);
我试图让所有属于Story的元素都不是私有的,根据我在这里看到的一些post( 1,2,3 ),解决方法是使用_story.isPrivate和find。 我目前正在这样做:
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)。 没有条件,查找返回所有元素,并正确填充_story。 我也激活了debugging输出查看正在执行的查询,我得到这个:
Mongoose: elements.find({ '_story.isPrivate': false }) { fields: undefined, safe: undefined }
试图在MongoDB中执行这个我没有得到任何结果。 这里有什么可能是错的?
谢谢
听@JohnnyHK。 他说的是实话。 Mongodb查询一次只能使用一个数据集合中的数据。 由于'elements'集合中的文档没有_story.isPrivate
关键字path,因此Element.find({'_story.isPrivate': false})
将永远不会匹配任何文档。 MongoDB中没有join。 真。 但是,考虑到“不join”约束,仍然可以构build一个应用程序并满足使用情况,但是您需要其他模式和查询devise。 有时候,人们将数据归一化,重复数据。 有时你运行多个相关的查询等等
你可以重新订购你的模型,并有
var storySchema = new mongoose.Schema({ title: {type: String, default: '', trim: true}, isPrivate: {type: Boolean, default: false}, elements: [{type: mongoose.Schema.Types.ObjectId, ref: 'Element'}] }); Story.distinct('elements', {'isPrivate':false}, function(error, results) { /* handle callback */ }
通过这种方式,您可以发出一个呼叫,并得到一个元素的集合。
- 在快速应用程序中使用Nunjucks
- 请求开发模式localhost中的Next.js应用程序在不同端口上运行的Graphql API
- MEANJS请求对象中的mongoose模型
- Express Postfunction中callback的执行顺序
- 在express.js app.params()和router.params()之间有什么不同?
- 从Node和Express后端将file upload到S3
- 为什么调用node.js body-parser失败,尽pipe我已经安装了它?
- 在使用PassportJS的Session中修改user.username
- 用jade在节点中加载fullCalendar的事件