[英]Mongoose (mongodb) $push data as subdocument, validate unique?
I have a User document which has a Notes subdocument. 我有一个包含Notes子文档的用户文档。 I'm using the following code to push new notes for the user with the given email address.
我正在使用以下代码为具有给定电子邮件地址的用户推送新笔记。
UserSchema.statics.addNotesToUser = function (email, notes, callback) {
return this.updateOne(
{'email': email},
{$push: {notes}},
callback
)
};
This is working fine, however it's ignoring my unique constraint on the NoteSchema. 这工作正常,但是忽略了我对NoteSchema的唯一约束。 these are my schemas
这些是我的模式
const NoteSchema = new Schema({
_id: false,
id: {type: String, required: true, trim: true, unique: true},
content: {type: String, required: true, trim: true, lowercase: true},
added: {type: Date, default: Date.now},
used: {type: Date, default: Date.now},
book: {
name: {type: String, required: true}
}
});
const UserSchema = new Schema({
email: {type: String, required: true, trim: true, lowercase: true, unique: true},
notes: [NoteSchema]
});
I'm wondering how I can make sure that when pushing new notes to my user, I can validate if the ID of the notes is unique.
我想知道如何确保在向用户推送新笔记时可以验证笔记ID是否唯一。
Thank you. 谢谢。
To achieve uniqueness constraint like functionality in subdocuments, hope that's OK. 要实现子文档中的功能之类的唯一性约束,希望可以。
let notesId = [];
notes.forEach(function(val,index){
notesId.push(val.id)
})
db.yourCollection.update(
{ 'email': email, 'NoteSchema.id': { '$ne': { $each: notesId } }},
{$push: {notes} },
callback)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.