express - 如何将对象数组添加到 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);
});
};
解决方案
您需要通过邮递员或您使用的任何应用程序来访问您的数据库以获取食品数组。
例子:
items: [req.body.theNameYouWant],
在邮递员中:
theNameYouWant: {name:"Hot dog",price: 3,...(你必须把FoodItemSchema的所有属性放在这里)}
否则,您还可以使用 $addToSet $push 等运算符,这将允许您在数组中引入 FoodItemSchema。
推荐阅读
- javascript - 从 iframe 上下文运行 document.referrer 不会在 Safari 12 中返回完整 URL
- android - 如何在特定位置替换 ViewPager 中的图像
- git - 使用 HTTPS 从 gitlab CI 作业克隆私有 Repo,而不将我的凭据暴露到 CLI
- docker - 无法在 docker-compose 中使用主机名访问 rails-api 后端
- angular - Angular CLI 终止
- java - java - 如何获取我在java中的onClick之类的方法中设置的值?
- python - 为什么一串单词的某些字符丢失而不是?
- python - 如何将与列表的完全匹配从一个数据框列提取到另一列?
- ios - 无法从 iOS 应用中的“共享”接收网站 URL 和粘贴文本
- python - 在python中一次删除多行