[英]Update an array of objects that contains a unique value using Mongoose
我在包含一组对象的集合中有文档。 数组中的每个对象都包含一个唯一的字段“clinic_id”。 我也在使用猫鼬唯一验证器。
我有一个 Node 路由,它接受一个 JSON 请求来将一个新对象推送到数组上。 但是,只要数组中有现有对象,这就会失败。 我在已经存在的对象上得到一个唯一的约束错误。 例如,如果我在数组中有一个带有 Clinic_id 1 的对象,并且我尝试为 Clinic_id 2 添加一个对象,我将收到一个错误,抱怨 Clinic_id 1 已经存在。 它的行为就像我试图创建一个重复的条目,而不仅仅是向数组添加一个新的非重复对象。
猫鼬模式的一个例子:
name: { type: String, required: true },
org_id: { type: String, unique: true, required: true },
branch: [{
name: { type: String, required: true },
clinic_id: { type: String, unique: true, required: true },
type: { type: String }
} ]
尝试将新对象推送到数组的节点路由中包含的代码示例:
const orgId = req.params.id;
Org.findOne({ org_id: orgId }).then(org => {
// Get org_id from URL and add to JSON body
req.body.org_id = orgId;
// Push Branch Object onto the array
org.branch.push(req.body);
org
.save()
.then(savedOrg => {
res.json({ status: 'SUCCESS', id: savedOrg._id });
})
.catch(err => {
const error = JSON.stringify(err);
res.status(500).json({ status: 'ERROR', desc: error });
});
});
mongoose-unique-validator 产生的错误文本:
{ ValidatorError: 错误,期望
clinic_id
是唯一的。 值:100
在新的 ValidatorError ...
附加信息:Node v10.15.1 / mongoose 5.2.1 / mongoose-unique-validator 2.0.2
您应该创建一个具有以下属性的新模型:
{
name: { type: String, required: true },
clinic_id: { type: String, unique: true, required: true },
type: { type: String }
}
现在,它更容易了,因为您不需要独立参考诊所。 您可以在本文档中添加 Org 的 id,但根据您的原始实现,我假设您不需要它。
当您去创建诊所时,您只需将 id 添加到父文档(Org)。
您组织中的字段将更改为:
branch: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Clinic'
}]
现在,无论何时创建分支,您只需将结果对象(您甚至不需要指定 _id,它会为您完成)推送到正确的组织中,您将拥有所需的列表。
当你想找到分支时:
Org.find(condition).populate('branch')
你会得到你想要的完全相同的结果。
现在,当我提到mongoose
,我的意思是如果你像这样导入它:
const mongoose = require('mongoose');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.