首页 > 解决方案 > 如何将对象数组添加到 mongoDB 模型

问题描述

我有一个代表餐厅菜单的模型,在该模型中,我有一个用于菜单中项目的数组。我不确定如何使用 express 将菜单项添加到我的菜单模型中,我将不确定要写什么的行加粗。

这是菜单模型:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const FoodItemSchema = new Schema({
  name: { type: String, required: true },
  price: { type: Number, required: true },
  Category: { type: String, required: false },
  Quantity: { type: String, required: false },
});

const MenuSchema = new Schema({
  restaurant_id: { type: mongoose.Schema.Types.ObjectId, ref: "restaurant" },
  items: [FoodItemSchema],
  dateCreated: { type: String, required: false },
});

module.exports = mongoose.model("menu", MenuSchema);

这是我用来向数据库添加菜单的快速函数,我不确定要为函数中的菜单项数组添加什么。

exports.sendMenuData = (req, res) => {
  const menu = new Menu({
    restaurant_id: req.body.restaurant_id,
    **items: [FoodItemSchema]**, //Not sure what to write here in terms of req 
    dateCreated:req.dateCreated,
  });
  menu
    .save()
    .then((data) => {
      console.log(data);
      res.send(data);
    })
    .catch((err) => {
      console.log(err);
    });
};

标签: expressmongoose

解决方案


您需要通过邮递员或您使用的任何应用程序来访问您的数据库以获取食品数组。

例子:

items: [req.body.theNameYouWant],

在邮递员中:

theNameYouWant: {name:"Hot dog",price: 3,...(你必须把FoodItemSchema的所有属性放在这里)}

否则,您还可以使用 $addToSet $push 等运算符,这将允许您在数组中引入 FoodItemSchema。


推荐阅读