I am trying to update my mongodb database by Id but I am getting error userId.save
is not a function. What I did was get all the databases data by Object.findById
then used Object.assign
to assign an updated value to the specified key then saved the updated Object back to the database. Where did I go wrong. How can I update a mongodb object by Id. Thanks in advance.
const Users = require('pathToSchema')
const userId = Users.findById('ObjectId')
Object.assign(userId, '{"email": "[email protected]"}')
//error arrises here. "userId.save is not a function"
userId.save()
.then((result) => {
console.log(result)
})
.catch((err) => {
console.log(err)
})
CodePudding user response:
The findById
is not execute yet. You have to use it with a callback
or an exec()
. You can learn more at mogoose doc.
Try change line const userId = Users.findById('ObjectId')
to const userId = await Users.findById('ObjectId').exec()
. exec()
will return a promise, so you could use await
to get result.
Furthermore, the Object.assign
statement is not correct, there is no need for the string character (which is '). It's just Object.assign(userId, {"email": "[email protected]"})
CodePudding user response:
Try assigning the email
prop instead of using Object.assign
. Also bear in mind that you need to assign 2 objects but you assign a string instead.
Try this:
const userId = Users.findById('ObjectId')
userId.email = '[email protected]';
userId.save()
.then((result) => {
console.log(result)
})
.catch((err) => {
console.log(err)
})
Also, make sure you create a model from the schema and use it to findById
. For instance:
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();