How to add item to mongoose Array

I'm developing a web app that uses mongodb database using mongoose in node.js... Now, I'm trying to build the rate feature, in this feature, people can rate the store and give some comments about that store. This is the structure:

rate: {
  author: req.body.author,
  text: req.body.text
}

To update it I'm using the "findOneAndUpdate" function, but, Always when i do it, the existent rate is overwritten by the new... Can you guys help me?

Upvotes: 0

Views: 1871

Answers (3)

user14520680
user14520680

Reputation:

One way is with regular JS, you can simply store the document you want to update in a variable. Then, use the push method on the rate field before calling save on the variable.

Upvotes: 0

Chanuka Sandeepa
Chanuka Sandeepa

Reputation: 720

Try this one

The model

const schema = new mongoose.Schema({
    name: String,
    description: String,
    price: Number,
    rating: [{
       author : String,
       text : String
    }]
    
});

module.exports = mongoose.model('Product', schema );

In request handler

const Product = require('./models/product');

const { id } = req.params; //product ID
const { author, text } = req.body;

const product = Product.findById(id);

product.rating = [...product.rating,{ author, text }]
product.save();

Upvotes: 0

Prathamesh More
Prathamesh More

Reputation: 1489

Here you can do. I am just demonstrating with example

Model

//Model
const ratingSchema = new mongoose.Schema({
    author: { type: String, required: true },
    text: { type: String, required: true }
});

const productSchema = new mongoose.Schema({
    name: { type: String, required: true },
    description: { type: String },
    rating: [ratingSchema],
    price: { type: Number, default: 1 },
});

module.exports = mongoose.model('Product', productSchema );

Now you can just push a new array

Controller

const ProductModel = require('./models/product');

const { id } = req.params;
const { author, text } = req.body;

PersonModel.update(
    { _id: id }, 
    { $push: { rating: { author, text }} },
    done
);

More about: https://mongoosejs.com/docs/api/array.html#mongoosearray_MongooseArray-push

Upvotes: 3

Related Questions