【问题标题】:Searching Embedded Objects in Mongoose在 Mongoose 中搜索嵌入对象
【发布时间】:2012-01-13 11:48:20
【问题描述】:

例如,如果我有以下架构(为简洁起见,非常简化)。如何按标签搜索帖子?如果嵌入了标签文档集合,我知道该怎么做,但我想将标签保留在他们自己的集合中。

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);
    });

【问题讨论】:

  • 你的代码中不应该是Post.find({'tags.name':'javascript'})吗?
  • 是的,里卡多。我试图去掉不相关的东西,把错误的查询放在那里。感谢收看

标签: mongodb node.js mongoose


【解决方案1】:

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

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

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);
    });
  }
);

【讨论】:

  • 我很抱歉我的初始代码 sn-p 具有误导性。在发布之前,我已经尝试过您的方法,但是如果您使用嵌入的 ObjectId 数组,而不仅仅是嵌入文档,那么上面的内容将不起作用。
【解决方案2】:

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

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

// ...

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

【讨论】:

  • 在这种情况下,我认为您是正确的。从那以后,我重新考虑了更接受的字符串数组方法。并使用此处概述的 mapreduced 集合link 来获取计数和唯一标签等。必须摆脱关系数据库的思维定势。
猜你喜欢
  • 2017-05-21
  • 2011-09-06
  • 2023-01-05
  • 1970-01-01
  • 1970-01-01
  • 2015-11-10
  • 2023-04-01
  • 2020-06-15
  • 1970-01-01
相关资源
最近更新 更多