mongoose查询字典数组

时间:2013-05-13 18:17:29

标签: node.js mongodb mongoose

如何使用包含词典的数组?我正在尝试将所有post字段聚集在一起,以便我可以搜索他们的文本。

我尝试使用mongo shell无处可去。

User.Blog().find({}).where('post').in(writing).exec(function (err, result) {
  //do something with results
}); // doesn't work

架构(编辑:从@JAM评论修复)

var blogSchema = new mongoose.Schema({
  group:  String,
  writing: [{
        post: String,
        name : Number
        }]
});

var Blog = mongoose.model('Blog', blogSchema);

更新:添加json数据和使用mongo shell将数据放入mongodb的命令:

{
  group:  "Design Writing",
  writing: [{
        post: "A very very very short post.",
        name:  10
  }, {
        post: "An early morning post about everything.",
        name:  11
  }]
}

* 或者,这里作为一行插入名为my_collection的集合中的数据库:*

db.my_collection.insert( {group:  "Design Writing", writing: [{post: "A very very very short post.",name:  10}, {post: "An early morning post about everything.",name:  11}]} )

1 个答案:

答案 0 :(得分:5)

writing数组中的对象被视为sub/embedded-documents。这意味着当它们存储在数据库中时会为它们分配_id

因此,有几种方法可以根据这些子文档查询Blog

var ObjectId = mongoose.Types.ObjectId;

// Assuming these objects are in the 'writing' array of a Blog
var postObject = { post: 'some text', name: 10 },
    postObjectWithId = { _id: new ObjectId(), post: 'some text', name: 10 };

// Example #1 Works!
Blog.find({'writing.post': postObject.post})
    .exec(function(err, res){ onBlogResult("Ex#1", err, res) });

// Example #2 Works!
Blog.find({})                        
    .where('writing').in([postObjectWithId])
    .exec(function(err, res){ onBlogResult("Ex#2", err, res) });

// Example #3 Works - its the same as example #2!
Blog.find({'writing': { $in: [ postObjectWithId ]}})
    .exec(function(err, res){ onBlogResult("Ex#3", err, res) });

// Example #4 Fails because of missing _id on postObject!
Blog.find({'writing': { $in: [ postObject ]}})
    .exec(function(err, res){ onBlogResult("Ex#4", err, res) });

如您所见,如果您拥有完整对象(包括find),则只能使用包含in元素的数组的_id个对象。

您可以在此GIST上查看整个来源 - 自行测试:)

希望这会有所帮助:)

Read the mongoose docs here