如何将项目添加到猫鼬数组 [英] How to add item to mongoose Array

查看:44
本文介绍了如何将项目添加到猫鼬数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个使用 mongodb 数据库的 Web 应用程序,在 node.js 中使用 mongoose...现在,我正在尝试构建评分功能,在此功能中,人们可以对商店进行评分并对该商店发表评论.这是结构:

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
}

要更新它,我正在使用findOneAndUpdate";功能,但是,总是当我这样做时,现有率会被新的覆盖率......你们能帮帮我吗?

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?

推荐答案

在这里你可以做到.我只是举个例子

Here you can do. I am just demonstrating with example

型号

//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

控制器

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

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

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

更多信息:https://mongoosejs.com/docs/api/array.html#mongoosearray_MongooseArray-push

这篇关于如何将项目添加到猫鼬数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆