[英]Node.js MongoDB Find with projection to exclude _id still returns it
尝试按照此处的示例通过使用投影来排除 _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, name: 'John', address: 'Highway 71' }, { _id: 5a2bb2d6ee48575cb54c436d, name: 'Susan', address: 'One way: .54b, name, {685c}54b, .54b, 75c }, { _id: 5a2bb2d6ee48575cb54c436d : 'Chuck', address: 'Main Road 989' }, { _id: 5a2bb2d6ee48575cb54c4372, name: 'Viola', address: 'Sideway 1633' } ]
理论上 _id 不应该是返回内容的一部分。 这里有什么问题?
要限制您必须使用fields
选项的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();
});
在 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.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; } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.