【问题标题】:Node.js MongoDB Find with projection to exclude _id still returns itNode.js MongoDB Find 与投影以排除 _id 仍然返回它
【发布时间】:2017-12-09 18:59:37
【问题描述】:

尝试按照示例here 进行过滤,使用投影排除_id。 _id 仍然返回:

代码

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/db1";

MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    var dbase = db.db("db1"); //here    

    dbase.collection("customers").find(
        {},
        {
            _id: 0

        }
        ).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
    });

});

结果仍然返回如下:

[ { _id: 5a2bb2d6ee48575cb54c4365, 名称:“约翰”, 地址:'Highway 71'},{_id:5a2bb2d6ee48575cb54c436d, 名称:“苏珊”, 地址:'单向 98' }, .... { _id: 5a2bb2d6ee48575cb54c4371, 名称:'查克', 地址:'主路 989' }, { _id: 5a2bb2d6ee48575cb54c4372, 名称:'中提琴', 地址:'Sideway 1633' } ]

理论上 _id 不应该是返回内容的一部分。这里有什么问题?

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    要限制你必须使用fields选项的字段(不知道新的更新):

    dbase.collection("customers").find({}, {
        fields: { _id: 0 }
    }).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
    });
    

    更新:

    对于版本 > 3,您必须改用 projection 选项:

    dbase.collection("customers").find({}, {
        projection:{ _id: 0 }
    }).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
    });
    

    【讨论】:

    • 终于找到了我想要的答案!知道为什么我在文档中没有找到有关此“字段”键的任何信息吗?
    • 终于也找到了答案。官方文档没有说明任何关于“字段”的内容
    【解决方案2】:

    在 MongoDB API 版本 3 中,fields 选项已被弃用。您现在应该改用projection 选项。

    例如:

    dbase.collection('customers').find({}, {
        projection: {
            _id: 0
        }
    }).toArray(function (err, result) {
        if (err) {
            throw err
        }
    
        console.log(result)
        db.close()
    })
    

    可在此处找到支持的选项的完整列表:http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#find

    【讨论】:

      【解决方案3】:

      从 3.4 版开始,现在可以选择在 find() 之外添加 .project()。

      使用 ES8 异步,等待。

      例如:

      async function connectDB(url) {
      
        try {
          const db = await MongoClient.connect(url);     
          const dbase = db.db("db1"); //here  
          
          const results = await dbase.collection("customers").find().project({_id:0}).toArray();
      
             console.log(result);
             db.close();
        }
        catch(err) {
          throw err;
        }
       }

      文档here 和另一个示例here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        • 2016-02-28
        • 1970-01-01
        相关资源
        最近更新 更多