【问题标题】:Mongoose select fields (nested)猫鼬选择字段(嵌套)
【发布时间】:2013-10-07 20:31:57
【问题描述】:

我正在尝试使用 mongoose 中的选择运算符为以下对象选择某些字段:

{
    "_id" : ObjectId("5249bb97a5de48bda3000003"),
    "id": 1,
    "geometry" : {
        "coordinates" : [
            1,
            1
        ],
        "type" : "Point"
    },
    "properties" : {
        "TYPE" : "Some Type",
            "TIMESTAMP": ......
    },
    "type" : "Feature"
}

我想 mongo 只返回 'properties.TYPE' 和 properties.TIMESTAMP 字段。我可以使用以下查询在 mongo 中执行此操作:

db.features.find({id: 1}, {'properties.TYPE': 1, 'properties.TIMESTAMP': 1})

我正在尝试使用 mongoose 中的 select 语句来做同样的事情: 变量字段 = { 属性:{ OBJECTID:1,TIMESTAMP:1 } } var query = Feature.find({id: 1}).select(fields);

Mongo 在尝试这样做时会引发错误,因此我不确定 mongoose 是否正确格式化嵌套字段对象。

这是正确的做法吗?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您可以在 select 对象中使用与 find 示例中相同的点符号样式和 Mongoose:

    var fields = { 'properties.OBJECTID': 1, 'properties.TIMESTAMP': 1 };
    var query = Feature.find({id: 1}).select(fields);
    

    您也可以使用 Mongoose 样式选择字符串:

    var query = Feature.find({id: 1})
        .select('properties.OBJECTID properties.TIMESTAMP');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-30
      • 2016-06-20
      • 2016-03-24
      • 2021-03-23
      • 2020-06-04
      • 2019-03-22
      • 2018-06-23
      • 1970-01-01
      相关资源
      最近更新 更多