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)
})
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;
3
Answers
This worked for me.
Try assigning the
email
prop instead of usingObject.assign
. Also bear in mind that you need to assign 2 objects but you assign a string instead.Try this:
Also, make sure you create a model from the schema and use it to
findById
. For instance:The
findById
is not execute yet. You have to use it with acallback
or anexec()
. You can learn more at mogoose doc.Try change line
const userId = Users.findById('ObjectId')
toconst userId = await Users.findById('ObjectId').exec()
.exec()
will return a promise, so you could useawait
to get result.Furthermore, the
Object.assign
statement is not correct, there is no need for the string character (which is ‘). It’s justObject.assign(userId, {"email": "[email protected]"})