I am implementing a function using node.js to update a value in mongoDB. Below is my mongoDB collection,
I want to update the values of the totalRating and totalVotes inside the ratings array. Therefore, I implemented the function as below in node.js.
router.post('/addReview', (req, res) => { Product.findOneAndUpdate( {_id: req.body.productId}, { "$set" : { "ratings.totalRating": req.body.rating, "ratings.totalVotes" : req.body.votes } }, {new : true}, (err, productInfo) => { if(err) return res.json({success:false, err}); res.status(200).json(productInfo) } ) }); Below is the Product Schema,
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const AddItemsSchema = new Schema({ _id: {type:String, required:true}, img: {type:String, required: true}, category: {type:String, required: true}, name: {type:String, required: true}, description: {type:String, required: true}, price: {type:String, required: true}, quantity: {type:String, required: true}, size: {type:String, required: true}, meterial: {type:String, required: true}, discount:{type:Number, default: 0}, comment:{type:Array, default: []}, ratings:{type:Array, required: true} }); const Products = mongoose.model('additems', AddItemsSchema); module.exports = Products; When I sent a post request using postman, it does not update the db values and it returns null. Can someone please point me out where I am doing wrong? Thanks!
Postman request body,
{ "productId": "5eb82cd3e8b80155fc3ee021", "rating" : 4.0, "votes" : 1 } 