我想从结果中排除一些属性。我阅读了规范:https : //docs.mongodb.com/manual/tutorial/project-fields-from-query-results/ - 我需要使用project函数。所以我链接了这个调用,但代码开始失败。没有.project({ auth: 0, prefs: 0, consent: 0 }). 问题出在哪里?我发现这个答案看起来很相似:https : //stackoverflow.com/a/51732851/1639556。
包.json
"mongodb": "^3.4.1",
Run Code Online (Sandbox Code Playgroud)
拉姆达
exports.handler = (payload, context, callback) => {
const userId = payload.pathParameters.userId;
context.callbackWaitsForEmptyEventLoop = false;
mongo.connectToDatabase()
.then(db => {
return findUser(db, userId);
})
.then(user => {
console.log("User fetched");
})
};
function findUser(dbClient, userId) {
return dbClient.db()
.collection("users")
.findOne({ "_id": userId })
.project({ auth: 0, prefs: 0, consent: 0 })
.then(doc => { return doc; });
}
Run Code Online (Sandbox Code Playgroud)
错误
2020-01-28T11:52:34.555Z 0701f485-3770-1f43-f838-4baec8377293 INFO Request failed TypeError: dbClient.db(...).collection(...).findOne(...).project is not a function
at findUser (/var/task/src/handlers/users/getUser.js:41:10)
at mongo.connectToDatabase.then.db (/var/task/src/handlers/users/getUser.js:19:20)
Run Code Online (Sandbox Code Playgroud)
PS我很好奇投影是在客户端还是服务器端完成的。这个project函数在find调用之后让我感到困惑。
.project()是一个游标函数,因此虽然您可以在游标方法上使用它,findOne但不返回游标。您可以做的是将project用作查询选项。
在您链接的文档中,有一个如何使用它的示例,如下所示:
db.inventory.find( { status: "A" }, { item: 1, status: 1, instock: { $slice: -1 } } )
Run Code Online (Sandbox Code Playgroud)
投影选项是{ item: 1, status: 1, instock: { $slice: -1 } }。
因此,在您的情况下,您需要将代码更改为:
return dbClient.db()
.collection("users")
.findOne({ "_id": userId }, { auth: 0, prefs: 0, consent: 0 })
.then(doc => { return doc; });
Run Code Online (Sandbox Code Playgroud)
或者,如果您使用 3+ 版的 Mongod nodejs 驱动程序更改为:
return dbClient.db()
.collection("users")
.findOne({ "_id": userId }, {projection: { auth: 0, prefs: 0, consent: 0 }})
.then(doc => { return doc; });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1623 次 |
| 最近记录: |