Node.js MongoDB Find with projection to exclude _id still returns it

后端 未结 3 1040
醉酒成梦
醉酒成梦 2020-12-18 18:03

Trying to follow the examples here to filter by using a projection to exclude _id. The _id still returns:

Code

var MongoClient = require(\'mongodb\')         


        
相关标签:
3条回答
  • 2020-12-18 18:40

    In version 3 of the MongoDB API, the fields option has been deprecated. You should now use the projection option instead.

    For example:

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

    The full list of supported options can be found here: http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#find

    0 讨论(0)
  • 2020-12-18 18:41

    To limit the fields you have to use fields option( dont know about new updates):

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

    UPDATE:

    For version > 3 you have to use projection option instead:

    dbase.collection("customers").find({}, {
        projection:{ _id: 0 }
    }).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
    });
    
    0 讨论(0)
  • 2020-12-18 18:44

    Starting in version 3.4, there is now an option for adding .project() outside of find().

    Using ES8 async,await.

    Ex:

    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;
      }
     }

    Docs here and another example here.

    0 讨论(0)
提交回复
热议问题