当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Only embed unique elements with mongoose

问题描述:

I use $addToSet because I don't want any duplicates.

children = children.map(child => new ChildModel({

a: child.a,

b: child.b

}));

ParentModel.findByIdAndUpdate(parentModelId, {

$addToSet: {

children: {

$each: children

}

}

}, (err, doc) => {

// ...

});

But if I use the code above, the code snippet new ChildModel() will cause it to assign an automatically created id to each element, so all the elements will, naturally, be unique.

How can I make sure that I don't add multiple elements to the field children with the same values a and b?

Edit

Model Schemas

const childrenModelSchema = new Schema({

a: Schema.Types.ObjectId,

b: Schema.Types.ObjectId,

c: [String]

});

const parentModelSchema = new Schema({

children: [childrenModelSchema]

});

分享给朋友:
您可能感兴趣的文章:
随机阅读: