我正在尝试使用Mongoose和NodeJS更新数据库中的数据,我已经可以从已登录的用户那里获取数据,但不会让我更新。在前端,我呈现了一个表单,该表单从登录的用户(views / pages / profile-edit.ejs)中获取数据。
在后端user.js文件中,我有这个:
.get('/profile-edit', auth, (req, res) => {
try {
const user = req.user
res.render('pages/profile-edit', { user } )
} catch (err) {
res.status(500).send(err)
}
})
.post('/profile-edit', auth, async (req, res) => {
try {
const user = req.user
await user.findOneAndUpdate()
res.redirect('/profile')
} catch (err) {
res.status(500).send(err)
}
})
在.post文件中,我将登录用户存储在const用户中。在waiting user.findOneAndUpdate中,我尝试更新,但是我什么也不做。我只重定向到我的个人资料页面。我没有收到任何错误,但是数据库中的数据没有更新。
这是我的猫鼬模型:
const userSchema = new mongoose.Schema({
firstname: {
type: String,
required: true
},
surname: {
type: String,
required: true
},
age: {
type: Number,
required: true
},
gender: {
type: String,
required: true
},
club: {
type: String,
required: true
},
image: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
searchGender: {
type: String,
required: true
},
description: {
type: String,
required: false
},
tokens: [{
token: {
type: String,
require: true
}
}]
})
// SOURCE : https://medium.com/swlh/jwt-authentication-authorization-in-nodejs-express-mongodb-rest-apis-2019-ad14ec818122
// This code is running bevore we save the object to the database. Here we hash the password with the package bcrypt.
userSchema.pre('save', async function (next) {
const user = this
if(user.isModified('password')){
user.password = await bcrypt.hash(user.password, 8)
}
next()
})
// Here we create a token with JWT. The sign expects data that will be used to sign the token.
// Once the token created save it to the list of tokens and return the token.
userSchema.methods.generateAuthToken = async function() {
const user = this
const token = jwt.sign ({_id: user._id}, process.env.JWT_KEY)
user.tokens = user.tokens.concat({token})
await user.save()
return token
}
// Here we search for the User we expext 2 parameters email & password. First search for the user by email, if we can't find it throw an error.
// If it is found we compare the password with the hashed password in the database.
userSchema.statics.findByCredentials = async (email, password) => {
const user = await User.findOne({ email })
if (!user) {
throw new Error({ error: 'Geen geldig emailadres gevonden in de database' })
}
const isPasswordMatch = await bcrypt.compare(password, user.password)
if (!isPasswordMatch) {
throw new Error({ error: 'Wachtwoord klopt niet' })
}
return user
}
// Here we create the model called User and bind it to the userSchema then we export it.
const User = mongoose.model('User', userSchema)
module.exports = User
这是我在GitHub上的仓库的链接,因此您可以查看整个代码GitHub Repo
先谢谢了。
答案 0 :(得分:1)
以下行是有问题的:
await user.findOneAndUpdate()
因为findOneAndUpdate是模型本身的一种方法(在这种情况下为User)。
为了能够使用findOneAndUpdate
方法,还需要一个过滤器和更新对象,以便它可以使用给定的过滤器查找文档,并使用更新对象更新其内容,如下所示:
User.findOneAndUpdate({username: ".."}, {firstname: "..."} );
您已经有传递给req.user的用户文档,所以我想您可以更新它的字段并使用save()方法。
.post('/profile-edit', auth, async (req, res) => {
try {
const user = req.user;
user.firstname = req.body.firstname; // this is just a sample, you may need to change it
await user.save();
res.redirect('/profile')
} catch (err) {
res.status(500).send(err)
}
})
如果这不起作用,则可以尝试使用findByIdAndUpdate方法,如下所示:
.post('/profile-edit', auth, async (req, res) => {
try {
const user = req.user;
await User.findByIdAndUpdate(user._id, {
firstname: req.body.firstname
})
res.redirect('/profile')
} catch (err) {
res.status(500).send(err)
}
})
答案 1 :(得分:0)
await User.findByIdAndUpdate(user._id, {
firstname: req.body.firstname},
{new: true}
)
新选项可确保返回修改后的文档而不是原始文档。默认情况下,“新”设置为false,因此请不要错过。