从一组对象中仅抓取一个对象

时间:2018-04-03 07:09:08

标签: node.js mongodb express mongoose mongodb-query

我正在使用MongoDB,我正在尝试根据其_id和所有兄弟元素来获取特定对象。例如,我的数组如下所示:

"blogs": [
    {
        "body": "default valuee",
        "header": "another first",
        "_id": "1234"
    },
    {
        "body": "second default value",
        "header": "second",
        "_id": "5678"
    }
]

我正在尝试获取 1234 的_id旁边的值(因此该对象的body,header和_id字段)。我尝试了一些Mongo查询,但没有运气。任何帮助都会很棒,欢呼声

我的功能是:

module.exports = function findBlog(db, id, callback){

var UserCollection = db.collection('users') //connect to business collection

UserCollection.findOne({ 'blogs._id': id }, {body: 1, header: 1, _id: { $elemMatch: { _id: id}}},function (err, user) {

    if (err){
        return callback({response: "3"})                              
    }else if(!user){
        return callback({response: "4"})
    }else {
        return callback({response: "2",data:user.blogs})
    }
  });
}

2 个答案:

答案 0 :(得分:1)

你应该使用这样的东西,

如果您想要博客和用户的所有字段,您可以直接使用

UserCollection.find({ 'blogs._id': id },  { blogs:{ $elemMatch:{ _id: id }}},function (err, user) {
        if (err){
            return callback({response: "3"})
        }else if(!user){
            return callback({response: "4"})
        }else {
            return callback({response: "2",data:user.blogs})
        }
      });
 }

如果您需要特定字段:

您将添加条件的第一个参数:{ 'blogs._id': id } 第二个参数您将添加所需的字段:{ "blogs.body": 1,"blogs.header": 1 }

UserCollection.findOne({ 'blogs._id': id }, { "blogs.body": 1,"blogs.header": 1 },function (err, user) {
    if (err){
        return callback({response: "3"})
    }else if(!user){
        return callback({response: "4"})
    }else {
        return callback({response: "2",data:user})
    }
  });
}

答案 1 :(得分:0)

正如我在对OP的问题的评论中所述,解决这个问题的最佳方法是创建博客集合。然后,您可以直接查询此集合,而不是查询用户集合。

通过将博客链接到用户,您仍可以在User模型中拥有blogs属性。 (参见populate上的Mongoose文档)