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
You have a typo. Change
foundProduct.OnSale = true;
withfoundProduct.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.
You have a typo error in the
foundProduct.OnSale
instead offoundProduct.onSale