猫鼬选择字段(嵌套)

los*_*ion 7 mongoose mongodb node.js

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

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

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

db.features.find({id: 1}, {'properties.TYPE': 1, 'properties.TIMESTAMP': 1})
Run Code Online (Sandbox Code Playgroud)

我试图在mongoose中使用select语句来做同样的事情:var fields = {properties:{OBJECTID:1,TIMESTAMP:1}} var query = Feature.find({id:1}).select(fields) ;

尝试这样做时,Mongo会抛出错误,因此我不确定mongoose是否正确格式化了嵌套字段对象.

这是正确的方法吗?

Joh*_*yHK 12

您可以在selectMongoose对象中使用相同的点符号样式,就像在find示例中一样:

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

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

var query = Feature.find({id: 1})
    .select('properties.OBJECTID properties.TIMESTAMP');
Run Code Online (Sandbox Code Playgroud)