gpt4 book ai didi

mongodb - 无法使用 Monk/Mongo 按名称找到用户

转载 作者:可可西里 更新时间:2023-11-01 10:42:19 26 4
gpt4 key购买 nike

我正在使用 Node、Mongo 和 Monk 开发一个 CRUD 应用程序。我想通过用户名找到一条记录,然后更新它。但我找不到记录,此代码无效:

// GET User Profile
router.get('/userprofile', function(request,response){
var db = request.db;
var userName = request.body.username;
var collection = db.get('usercollection');
collection.findOne({
"username": userName
},{},function(e,user){
response.render('userprofile', {
"user": user
});
});
});

“findOne”方法不返回任何内容,“user”对象最终为空。

最佳答案

findOne() 的签名中删除中间的空对象 查询工作的方法签名:

注意:您获取userName 的方式适用于当请求方法是POST 时,这里您执行的是GET,因此您需要使用request.query 属性。更多详情 here

var userName = request.query.username;
collection.findOne({"username": userName}, function(e,user){
response.render('userprofile', { "user": user });
});

如果你想更新那么你可以使用 update() 方法,假设您要更新 username 字段以将其更改为 'foo',以下 stub 显示了如何进行更新:

var u = collection.update({ "username": userName }, { "$set": { username: 'foo' } });
u.complete(function (err, result) {
console.log(err); // should be null
console.log(result); // logs the write result
});

关于mongodb - 无法使用 Monk/Mongo 按名称找到用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37291530/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com