【发布时间】:2019-02-12 13:40:01
【问题描述】:
首先,我对 MongoDB、Mongoose 和 Express 还是很陌生。我正在尝试创建一个 Mongoose 模型,它有两个数组,我想用多个名为 itemSchema 的对象填充这些数组,但我不确定我应该如何在不使用 findOneAndUpdate 的情况下更新数组,但因为我的数组最初是空的在创建文档之前没有初始 ID。使用我在下面定义的方法 - 食物数组中的任何现有数据都将替换为新数组。下面是我的模型 -
const mongoose = require("mongoose");
const itemSchema = new mongoose.Schema({
id: String,
drinks: [
{
id: String,
name: {
type: String,
required: true
},
price: {
type: String,
required: true
},
description: {
type: String
},
date: {
type: Date,
default: Date.now
}
}
],
food: [
{
name: {
type: String,
required: true
},
price: {
type: String,
required: true
},
description: {
type: String
},
date: {
type: Date,
default: Date.now
}
}
]
});
module.exports = Item = mongoose.model("item", itemSchema);
我不知道我是否正确定义了架构。我知道它不是很干燥(因为两个数组都包含相同的类型),但是因为我相信这是一个如此简单的用例,所以当我可以创建一个模式时,我不想为饮料和食物定义两个单独的模式.
router.post("/food", async (req, res) => {
try {
// Create an object from the request that includes the name, price and description
const newItem = {
name: req.body.name,
price: req.body.price,
description: req.body.description
};
// pass the object to the Items model
let item = new Items(newItem);
// add to the comments array
console.log("the new comment ", newItem);
item.food.unshift(newItem);
item.save();
// return the new item array to confirm adding the new item is working.
res.json(item);
} catch (error) {
// Display an error if there is one.
res.send(404).json(error);
}
});
上述方法的问题来自我应该如何更新数组。例如,我定义了下面的函数来更新食物数组,但每次都会创建一个新数组。我相信这与没有我可以用来为模型提供 findOneAndUpdate 方法的 Id 参数有关。任何帮助将不胜感激。提前谢谢你。
【问题讨论】: