-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Can I create unique index for subdocument? #2226
Comments
A combination of an index on the subdocument and the |
$addToSet is works, but it detect other subdocument in different parent too, correct me if i'm wrong, because i just tested it |
I guess I'm not understanding what you mean by subdocument in a different parent. Can you provide a code example that shows what you're trying to do? |
Sorry for the bump but when looking for a solution, I figured this could help in the future: const schema = new Schema({
value: String,
another: Number,
subdocs: [{
prop: String, /* Should be unique */
value: Number
}]
});
/**
* Check for duplicated sub document properties.
*/
schema.pre('validate', function validate(next) {
var unique = [];
for (var i = 0, l = this.subdocs.length; i < l; i++) {
let prop = this.subdocs[i].prop;
if (unique.indexOf(prop) > -1) {
return next(new Error('Duplicated sub document!'));
}
unique.push(prop);
}
next();
}); Explanation:Let's asume that we have a schema with a I know it's not super-efficient but it works. |
Sure that works most of the time, but keep in mind that when you do a |
@vkarpov15 The push is made to the |
Nah that's beside the point. Suppose you're trying to save 2 documents at roughly the same time from different JS programs - both do a |
@vkarpov15 good point, didn't thought it for simultaneous inserts. Well, this seems a lot more complex but I'll try to figure it out :) |
Well your approach works as long as you call |
I figured out something else that seems to work, even in simultaneous updates. Let's assume Model.update({
_id: '576328595b2880f831413b92',
'subdocs.name': {
$ne: 'Unique Name'
}
}, {
$push: {
subdocs: {
name: 'Unique Name'
}
}
}).then((raw) => {
// check raw.nModified value
}).catch(next); |
Great idea 👍 that should work well |
🙌 |
@stgogm you just ended a 5 hour search, and for that, I'm grateful. |
@vkarpov15 can you give me an example of how $addToSet can assure sub-document field uniqueness Ive tried this
|
@ksuhiyp const unitSchema = new Schema({ name: String, level: Number }, { _id: false })
|
Thanks to @vkarpov15 You saved me. |
Is it possible to create unique index for subdocument? I mean, it may duplicate in other subdocument, but not same parent,
The text was updated successfully, but these errors were encountered: