javascript - MongoDB:如何返回 JSON 中的特定字段和特定子文档

标签 javascript node.js mongodb mongodb-query

如果我有以下集合:

{
    "restaurant": {
        "_id": "5c0711f23533ef13a3e53d8b",
        "name": "burger king",
        "description": "american",
        "reservations": [
            {
                "_id": "5c0712503533ef13a3e53d8c",
                "time": "1:00 pm",
                "people": 3
            },
            {
                "_id": "5c0717129a8d7213e46d92da",
                "time": "9:30 am",
                "people": 10
            },
            {
                "_id": "5c071960160f2a13f647e100",
                "time": "12:30 am",
                "people": 25
            }
        ],
        "__v": 0
    }
}

如果我只想通过 POST 返回带有餐厅 _id、名称、描述的特定预订,例如:

{
    "restaurant": {
        "_id": "5c0711f23533ef13a3e53d8b",
        "name": "burger king",
        "description": "american",
        "reservations": [
            {
                "_id": "5c0717129a8d7213e46d92da",
                "time": "9:30 am",
                "people": 10
            }
        ],
        "__v": 0
    }
}

什么是最好的方法?

我试过:

Restaurant.find( {_id: ObjectID(id)}, {reservations : { $elemMatch: {time: time} }, {$elemMatch: {people: people}} } )
.then( (restaurant)=> {
    res.send({restaurant})
})

但不工作。 任何帮助将不胜感激

最佳答案

您的查询不正确。

匹配应该是这样的:

Restaurant.find( {_id: ObjectID(id)}, {
   name: 1, 
   description: 1, 
   reservations : { $elemMatch: {time: time, people: people} } } )
.then( (restaurant)=> {
    res.send({restaurant})
})

并确保 _id 实际上是 ObjectID 类型而不是 String

以下查询工作正常(本地测试):

db.getCollection('test').find({_id: '5c0711f23533ef13a3e53d8b'}, {name:1, description: 1, reservations: {$elemMatch: {people: 3, time: '1:00 pm'}}})

请注意,我使用的是字符串 _id 而不是对象 ID。

关于javascript - MongoDB:如何返回 JSON 中的特定字段和特定子文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53623586/

相关文章:

javascript - ReactJS - 在 React 类中初始化 jquery 插件的标准方法是什么?

javascript - 我想在特定行中显示特定类别的框

node.js - 如何访问 Mongoose 中静态方法内的实例模型?

mysql - 有没有人找到一种在 SQL 数据库中存储 BSON ObjectId 值的有效方法?

javascript - 如何删除mongodb数组中的逗号

angularjs - MongoDB 未通过 Mongoose 发布任何数据

javascript - 未获取单击的 href 标签的索引值

javascript - 替代css3而不是选择器

node.js - 未处理的拒绝 TypeError : Cannot read property 'name' of null

node.js - NodeJS发布主题时如何传递partitionKey或MessageId?