[英]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.