gpt4 book ai didi

node.js - TypeError : foundUser. lastLogin.update 不是一个函数

转载 作者:太空宇宙 更新时间:2023-11-04 01:49:52 25 4
gpt4 key购买 nike

每次用户登录时,我都会尝试更新我的 Mongoose 用户架构中上次登录的字段。

在用户模式中,我有这个,以便在创建用户时,最后一次登录是创建日期:

lastLogin: {
type: Date,
default: Date.now
}

在我的 route ,我尝试将 lastLogin 更新为用户登录的时间,但它要么返回更新不是函数,要么根本不起作用:

User.findById(req.user._id, function(err, foundUser) {
if (err) {
console.log(err);
} else {
console.log("Found user last login is ");
console.log(foundUser.lastLogin)

foundUser.lastLogin.update({$set: {'lastLogin': Date.now()}});

console.log("new last login is")
console.log(foundUser.lastLogin)
}
});

最佳答案

嗯,这就是你要做的

foundUser.update({$set: {'lastLogin': Date.now()}}, function(err,user){
console.log("new last login is")
console.log(user.lastLogin)

});

您正在做的是 lastLogin 上的 update,它没有任何 update 方法,因为它是属性而不是文档。

或者您可以使用 mongoose 版本 4+ 的 findByIdAndUpdate 来完成所有操作,例如

User.findByIdAndUpdate(req.user._id, { $set: { lastLogin: Date.now() }}, {new: true}, function(err,user){
console.log("new last login is")
console.log(user.lastLogin)

})

new: bool - true 返回修改后的文档而不是原始文档。默认为 false

关于node.js - TypeError : foundUser. lastLogin.update 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50123889/

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