在Mongoose中搜索嵌入式对象

Eri*_*ord 5 mongoose mongodb node.js

例如,如果我有以下Schema(为简洁起见,大大简化).如何通过标签搜索帖子?如果嵌入了标记文档集合,我知道如何执行此操作,但我想将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);
    });
Run Code Online (Sandbox Code Playgroud)

mpo*_*ien 5

您应该能够使用object.fieldmongoose 的表示法来查询嵌入的文档。但是,您可能需要确保您的嵌入式文档具有按顺序声明为模式一部分的所有字段(在您的示例中,您查询“comments.name”,但 PostSchema 没有注释字段 - 也许这导致了问题? )

我能够得到像这样工作的概念证明,它应该按原样成功运行:

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);
    });
  }
);
Run Code Online (Sandbox Code Playgroud)


Ric*_*asi 3

拥有标签架构是最好的方法吗?像这样更简单的东西应该可以工作:

Posts = new Schema({
    title: String
    body: String
    tags: [String]
})

// ...

Posts.find({ tags: { $in: ['javascript'] }, function(err, posts){
    console.log(posts)
})
Run Code Online (Sandbox Code Playgroud)