maison.m
maison.m

Reputation: 863

model.findByIdAndUpdate() is not updating

I am trying to add new data into a user model and have had a hard time trying to get findByIdAndUpdate() to work. It will not update the model with a new object.

Here is where I am calling findByIdAndUpdate() and trying to add an object:

    const User = require('../../models/api/user');

    const customer = {
        name: 'Quick Pizza & Subs',
        address: '1234 Example Lane',
        zip: 432123
    };

    User.findByIdAndUpdate(userId, customer, { new: true }, (err, user) => {
        if(err) { console.log(err) };
    });

In the above block of code, I can verify that I am finding the correct user with the userId variable. When I console.log(user) I get back the user I am looking for. I just can't figure out why the passed in object does not update to the found user collection.

User Schema:

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
    username: {
        type: String,
        default: ''
    },
    password: {
        type: String,
        default: '',
    },
    registerDate: {
        type: Date,
        default: Date.now()
    }
});

module.exports = mongoose.model('User', UserSchema);

According to the Mongoose docs this is all I need to do:

Model.findByIdAndUpdate(id, { name: 'jason bourne' }, options, callback)

In my code, I do not see what I am doing differently. I get no errors when I test the route in Postman. Can anyone shed some light on this?

Upvotes: 1

Views: 5933

Answers (3)

Matias Salimbene
Matias Salimbene

Reputation: 605

I had the same problem and was able to make it work by calling the method with await. Example below:

const updatedEmployee = await Employee.findByIdAndUpdate(
  _employeeID,
  {
    _businessUnits
  },
  {
    new: true
  }
);

Upvotes: 1

maison.m
maison.m

Reputation: 863

I had not added updated my User schema with a customer field. The working Schema is:

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
    username: {
        type: String,
        default: ''
    },
    password: {
        type: String,
        default: '',
    },
    customer: {
        type: Object,
        default: ''
    },
    registerDate: {
        type: Date,
        default: Date.now()
    }
});

module.exports = mongoose.model('User', UserSchema);

Upvotes: 4

Emad Dehnavi
Emad Dehnavi

Reputation: 3441

For updating what I usually use is this, I don't see you using $set anywhere in your code, I hope this help :

User.findByIdAndUpdate(
userId,
{
  $set: {
    customer
  }
},
{ new: true },
(err, user) => {
  if (err) return res.json(err)
  return res.json(user)
}
)

Upvotes: 0

Related Questions