skip to Main Content

I am unable to update and save a change in the database using mongoose. I am getting the same value for foundProduct twice when I console.log. What could be going wrong?

// Schema
const productSchema = new mongoose.Schema(
    {
        name: {
            type: String,
            required: true,
        },
        price: {
            type: Number,
            required: true,
        },
        onSale: {
            type: Boolean,
            default: false,
        },
    }
)

// model
const Product = mongoose.model('Product', productSchema)

const findProduct = async () => {
    const foundProduct = await Product.findOne({ name: 'Mountain Bike' });
    console.log(foundProduct)
    foundProduct.OnSale = true;
    await foundProduct.save().then((data) => console.log(data))
    // console.log(foundProduct)
}

findProduct();

2

Answers


  1. You have a typo. Change foundProduct.OnSale = true; with foundProduct.onSale = true;.

    Since you are using the wrong case, Mongoose considers OnSale to be an extra field. And because it’s not in your schema, it’s ignored when saving to db.

    Login or Signup to reply.
  2. You have a typo error in the foundProduct.OnSale instead of foundProduct.onSale

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