在Mongoose中searchembedded对象

例如,如果我有以下架构(为了简洁,大大简化)。 如何通过标签searchpost? 我知道如果这个标签文档集合被embedded,但是我想把Tag放在他们自己的集合中。

PostSchema = new Schema({ title: String body: String tags: [{type: Schema.ObjectId, ref: 'Tag' }] }); TagSchema = new Schema({ name: String }); // Here is what I've tried Post.find({'tags.name':'javascript'}) .populate('tags') // Is it necessary to join the collections? .run(function(err, posts) { console.log('posts: ', posts); }); 

有一个架构标签最好的方法? 像这样简单的东西应该工作:

 Posts = new Schema({ title: String body: String tags: [String] }) // ... Posts.find({ tags: { $in: ['javascript'] }, function(err, posts){ console.log(posts) }) 

您应该能够使用与mongooseobject.field表示法查询embedded式文档。 但是,您可能需要确保您的embedded式文档将所有字段按顺序声明为架构的一部分(在您的示例中,您在“comments.name”上查询,但PostSchema没有注释字段) – 也许这是导致问题的原因? )

我能够得到这样的概念certificate,它应该按原样运行:

 var mongoose = require('mongoose') var Schema = mongoose.Schema mongoose.connect('mongodb://localhost/testjs'); PostSchema = new Schema({ title: String, body: String, comments: [], tags: [{type: Schema.ObjectId, ref: 'Tag' }] }); TagSchema = new Schema({ name: String }); var Post = mongoose.model('Post', PostSchema); var mypost = new Post() mypost.title = "yo" mypost.body = "asfkjabfkjbsdf" mypost.comments = [{'name':'javascript', 'text':'sup'}] mypost.save( function(err){ // Save the post, and then read it back by querying the embedded field Post.find({'comments.name':'javascript'},function(err, posts){ console.log('posts: ', posts); }); } );