How to add item to mongoose Array

南笙酒味 提交于 2021-01-29 11:00:23

问题


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?


回答1:


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




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/64531122/how-to-add-item-to-mongoose-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!