【问题标题】:mongoose query for an array of dictionariesmongoose 查询字典数组
【发布时间】:2013-05-15 04:15:16
【问题描述】:

您如何处理包含字典的数组?我正在尝试将所有 post 字段放在一起,以便搜索它们的文本。

我使用mongo shell 的尝试一直没有成功。

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

模式(编辑:从@JAM cmets 修复)

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

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

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

    所以,有几种方法可以根据这些子文档查询Blogs:

    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 元素的数组来find 对象。

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

    希望这会有所帮助:)

    Read the mongoose docs here.

    【讨论】:

    • “postObj”中有什么内容?我尝试了“发布”,但这不起作用——更近了,但有些东西不对劲。我对链接感到困惑。 (是的,我在制作示例时输入了错误的架构。)
    • postObj 示例 { post: "heyho", name: 1 } - 正如您的架构指定的那样。我认为这行得通。
    • 嗯。还是行不通。 find() 有效,但我无法使用猫鼬深入到结构中。我会继续尝试,虽然我已经尝试了十几个版本。我可以通过在 exec 函数中明确写出以下内容来提取我需要的内容:var just_the_post = result[0]['writing'][0]['post'];D
    • 哦,好的。然后尝试.where('writing.post').equals(postObj.post) - 让我知道这是否有效:)
    • eeeks。对不起,你的意思是这样吗? find({}).where('writing.post').equals({ post: "heyho", name: 1 }.post) ?我不清楚 postObj 来自哪里!
    猜你喜欢
    • 2022-01-10
    • 2021-10-22
    • 2019-06-14
    • 1970-01-01
    • 2016-01-01
    • 2014-05-13
    • 2016-03-24
    • 2016-01-24
    • 2018-06-12
    相关资源
    最近更新 更多