Home > Net >  Product not updating - Mongoose MongoDB
Product not updating - Mongoose MongoDB

Time:03-23

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();

CodePudding user response:

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.

CodePudding user response:

Im not sure if you are trying to just update a value for the query, or if you are trying to make a copy of what you queried with a different value. Either way, heres how you do it.

//if you are trying to update the value of onSale for the mountain bike that you queried

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

const updateProduct = async () => {
    const foundProduct = await Product.updateOne({ name: 'Mountain Bike' }, {
      $set: {onSale: true}
    });
}

findProduct();

//if you are trying to create a copy with a different value for onSale of the mountain bike that you queried

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

const updateProduct = async () => {
    const foundProduct = await Product.updateOne({ name: 'Mountain Bike' });
    
    const newProduct = new Product({
      ...foundProduct,
      onSale: true
    })
    
    newProduct.save();
}

findProduct();

  • Related