根据id更新mongo数据库对象时出错



我正试图按Id更新我的mongodb数据库,但我收到错误userId.save不是函数。我所做的是通过Object.findById获取所有数据库数据,然后使用Object.assign为指定的键分配更新的值,然后将更新的Object保存回数据库。我哪里出错了。如何通过Id更新mongodb对象。提前感谢。

const Users = require('pathToSchema')
const userId = Users.findById('ObjectId')
Object.assign(userId, '{"email": "test@gmail.com"}')
//error arrises here. "userId.save is not a function"
userId.save()
.then((result) => {
console.log(result)
})
.catch((err) => {
console.log(err)
})

const mongoose = require('mongoose')
const Schema = mongoose.Schema
const users_Schema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
}
}, {timestamps: true})
const Users = mongoose.model('users', users_Schema)
module.exports = Users;

findById尚未执行。您必须将其与callbackexec()一起使用。你可以在mogoose doc了解更多
尝试将行const userId = Users.findById('ObjectId')更改为const userId = await Users.findById('ObjectId').exec()exec()将返回一个promise,所以您可以使用await来获得结果
此外,Object.assign语句不正确,不需要字符串(即'(。只是Object.assign(userId, {"email": "test@gmail.com"})

尝试分配email道具,而不是使用Object.assign。还要记住,您需要指定2个对象,但您需要指定一个字符串。试试这个:

const userId = await Users.findById('ObjectId')
userId.email = 'test@gmail.com';
userId.save()
.then((result) => {
console.log(result)
})
.catch((err) => {
console.log(err)
})

此外,请确保从模式创建一个模型,并将其用于findById。例如:

const UserSchema = new Schema({
name:String,
username:{type:String, required:true, index:{unique:true}},
password:{type:String, required:true, select:false}
});
const UserModel = mongoose.model('User', UserSchema);
const user = await UserModel.findById(...);
user.save();

这对我有效。

Users.findById('ObjectId')
.then((result) => {
Object.assign(result, {
"email": "test@gmail.com"
})
result.save()
.then((result) => {
console.log(result)
})
.catch((err) => {
console.log(err)
})
})
.catch((err) => {
console.log(err)
})

最新更新