node.js - NodeJs Mongoose 更新分类产品
问题描述
我有类别 mongoose 文档,我想更新他的产品。每次更新产品时只需重写它们,我只有最后一次放置记录。如何填充产品?
const category = new mongoose.Schema({
products: [{ type: mongoose.Schema.Types.ObjectId, ref: "Product" }],
});
module.exports = mongoose.model("Category", category);
exports.updateCategory = catchAsyncErrors(async (req, res, next) => {
let category = await Category.findById(req.params.id);
category = await Category.findByIdAndUpdate(req.params.id, req.body, {
new: true,
runValidators: true,
useFindAndModify: false,
})
res.send(200).json({
success: true,
category
});
});
解决方案
假设您的产品在正文中称为产品:
category = await Category.findByIdAndUpdate(req.params.id, { $push: { products: req.body.products } }, {
new: true,
runValidators: true,
useFindAndModify: false,
})
推荐阅读
- variables - Jenkins Pipeline:将 github 提交消息放入变量并保存在代理之间
- javascript - 无法读取未定义的属性“getElementById”
- java - 为什么堆用于管理java中的对象引用?
- c++ - 在eclipse中从linux编译windows
- excel - vba将所有docx extn文件从文件夹移动到另一个
- node.js - 使用由 jose4j HMAC_SHA256 生成的令牌在 node.js 中使用 jsonwebtoken 验证 JWT
- sql - 如何在 SQL Server 上将 1 行与多列转换为 2 行多列?
- reactjs - Testcafe + React + Browserstack
- javascript - 将函数更改为组件 React
- javascript - 将对象数组从数组转换为对象属性的对象