[英]Creating new mongoose sub-doc and appending to existing parent doc
I'm building a website with a database using NodeJS, MongoDB, Express, Mongoose etc.我正在使用 NodeJS、MongoDB、Express、Mongoose 等构建一个带有数据库的网站。
I nabbed (and adjusted) the below code from somewhere, so this is where I'm at...我从某个地方获取(并调整)了以下代码,所以这就是我所在的位置...
exports.addCategories = catchAsync(async (req, res, next) => {
const categories = req.body;
const length = categories.length;
const eventID = categories[length - 1].eventId;
categories.pop();
Event.findOne({ _id: eventID }, (err, event) => {
if (err) return res.status(400).send(err);
if (!event)
return res.status(400).send(new Error("Could not find that event"));
Category.create(categories, (err, category) => {
if (err) return res.status(400).send(err);
event.categories.push(category._id);
event.save((err) => {
if (err) return res.status(400).send(err);
res.status(200).json(category);
});
});
});
});
Currently the mongoose debug output is showing the following (which confirms that MOST of it is working, but the IDs just aren't being pulled correctly):目前 mongoose 调试输出显示以下内容(这证实了它的大部分工作正常,但 ID 没有被正确拉出):
> Mongoose: events.updateOne({ _id: ObjectId("614bc221bc067e62e0790875")}, { '$push': { categories: { '$each': [ undefined ] } }, '$inc': { __v: 1 }}, { session: undefined })
Nevermind!没关系! I realised that "category" was still an array, rather than an element of the categories array as I'd assumed.
我意识到“类别”仍然是一个数组,而不是我假设的类别数组的一个元素。
So I replaced that section with this, and now... it works!所以我用这个替换了那个部分,现在......它起作用了!
Category.create(categories, (err, categories) => {
if (err) return res.status(400).send(err);
categories.forEach((category) => {
event.categories.push(category._id);
});
event.save((err) => {
if (err) return res.status(400).send(err);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.