Trying to follow the examples here to filter by using a projection to exclude _id. The _id still returns:
Code
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();
});
});
Result still return as follows:
[ { _id: 5a2bb2d6ee48575cb54c4365, name: 'John', address: 'Highway 71' }, { _id: 5a2bb2d6ee48575cb54c436d, name: 'Susan', address: 'One way 98' }, .... { _id: 5a2bb2d6ee48575cb54c4371, name: 'Chuck', address: 'Main Road 989' }, { _id: 5a2bb2d6ee48575cb54c4372, name: 'Viola', address: 'Sideway 1633' } ]
Theoretically _id should not be part of what is returned. What is wrong here?
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();
});
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
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; } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.