node.js - Mongoose 查询字典数组

标签 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}]} )

最佳答案

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

因此,您可以通过几种方式根据这些子文档查询博客:

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

如您所见,如果您拥有完整的对象(包括 _id),则只能使用 in查找带有包含元素的数组的对象>).

您可以查看此 GIST 的完整源代码- 亲自测试一下:)

希望这有帮助:)

Read the mongoose docs here .

关于node.js - Mongoose 查询字典数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16528539/

相关文章:

django.core.exceptions.ImproperlyConfigured : name must be an instance of basestring

c++ - 在 OSX 10.10.5 上使用 mongo-cxx-driver 编译 C++ 文件时出错

node.js - Mongoose $lookup 对象返回空数组

node.js - 'req.body.username' 和 'req.body.password' 未定义

node.js - 如何在 MongoDB 上为部分文本搜索创建索引?

angularjs - 如果元素包含值,如何在 Protractor 中退出测试用例

node.js - Cat 显示日志中没有任何内容( express 服务器)

javascript - 控制台上的简单 node.js readline

javascript - 在 nodejs + express 中验证 URL 以处理错误的请求错误

mongodb - Pymongo 插入和查询引用