skip to Main Content

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


  1. Chosen as BEST ANSWER

    This worked for me.

    Users.findById('ObjectId')
      .then((result) => {
        Object.assign(result, {
          "email": "[email protected]"
        })
        result.save()
          .then((result) => {
            console.log(result)
          })
          .catch((err) => {
            console.log(err)
          })
      })
      .catch((err) => {
        console.log(err)
      })


  2. 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 = await 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();
    
    Login or Signup to reply.
  3. 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]"})

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search