node.js - 将数据保存到猫鼬中的数组
问题描述
用户可以发布其他用户可以请求的项目。因此,一个用户创建一个项目,许多用户可以请求它。所以,我认为最好的方法是将一组用户放入请求它的产品模式中。现在我只想存储用户 ID 和名字。这是架构:
const Schema = mongoose.Schema;
const productSchema = new Schema({
title: {
type: String,
required: true
},
category: {
type: String,
required: true
},
description: {
type: String,
required: true
},
userId: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
requests: [
{
userId: {type: Object},
firstName: {type: String}
}
],
});
module.exports = mongoose.model('Product', productSchema);
在我的控制器中,我首先找到该项目,然后调用 save()。
exports.postRequest = (req, res, next) => {
const productId = req.body.productId;
const userId = req.body.userId;
const firstName = req.body.firstName;
const data = {userId: userId, firstName: firstName};
Product.findById(productId).then(product => {
product.requests.push(data);
return product
.save()
.then(() => {
res.status(200).json({ message: "success" });
})
.catch(err => {
res.status(500).json({message: 'Something went wrong'});
});
});
};
首先,这样可以吗?我发现了一些关于此的帖子,但他们没有找到并调用 save,他们使用 findByIdAndUpdate() 和 $push。我这样做是“错误的”吗?这是我尝试的第二种方法,我在数据库中得到了相同的结果:
exports.postRequest = (req, res, next) => {
const productId = req.body.productId;
const userId = req.body.userId;
const firstName = req.body.firstName;
const data = {userId: userId, firstName: firstName};
Product.findByIdAndUpdate(productId, {
$push: {requests: data}
})
.then(() => {
console.log('succes');
})
.catch(err => {
console.log(err);
})
};
解决方案
以你的方式做这件事并没有错。在查询后使用保存使您有机会验证数据中的某些内容。并且您还可以添加其他字段(如果包含在架构中)。例如,如果您当前的 json 返回没有名为 last_name 的字段,那么您可以添加该字段并保存文档,这是一个好处..
使用 findById() 时,您实际上无权进行更改,除非您对其进行编程
我注意到的一件事..在您的架构中,使用 mongoose.modal() 编译它之后
导出已编译的模型,以便您可以在需要使用导入的任何地方使用它。像这样..
const Product = module.exports = mongoose.model('Product', productSchema);
推荐阅读
- python - 为什么这段 Python 代码不起作用?它不返回任何输出
- dialogflow-es - 如何在 DialogFlow 中的短语之间挑选活动
- java - ResourceBundle找不到BaseName gradle项目java
- javascript - 使用 React Suspense 和 React.lazy 子组件进行 Jest/Enzyme 类组件测试
- azure - Azure 是否自行决定取消分配最终用户的 VM?
- r - Editing data frame after reactive upload in R shiny
- xml - Making a XML-built component evoke a non-interface code
- java - 无法获得 go daddy ssl 证书以使用 spring boot
- ios - UISearchBar 清除按钮颜色变化
- spring - Spring Cloud 配置服务 - Git vs Native