mongoose查询字典数组

cat*_*aki 1 mongoose mongodb node.js

你如何使用包含字典的数组?我正在努力将所有post领域聚集在一起,以便我可以搜索他们的文本.

我的尝试继续无处使用mongoshell.

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

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

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

var Blog = mongoose.model('Blog', blogSchema);
Run Code Online (Sandbox Code Playgroud)

更新:添加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
  }]
}
Run Code Online (Sandbox Code Playgroud)

*或者,这里作为一行插入名为的集合中的数据库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}]} )
Run Code Online (Sandbox Code Playgroud)

JAM*_*JAM 5

writing数组中的对象被视为子/嵌入文档.这意味着_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) });
Run Code Online (Sandbox Code Playgroud)

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

你可以在这个GIST上查看整个源代码- 自己测试一下:)

希望这可以帮助 :)

在这里阅读mongoose文档.