Reputation: 533
I am using array to store ObjectId's but even the duplicate Id's are being saved
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const as = new Schema({
aId: [{
type: Schema.Types.ObjectId,
ref: 'js',
}],
jId: {
type: Schema.Types.ObjectId,
ref: 'jb',
},
});
as.index({ aId: 1 }, { unique: true });
module.exports = mongoose.model('applicants', as);
in database the aId ObjectId are stored as serially 0,1,2,3 on.... but even using index the id's are saved duplicately,
{
"_id" : ObjectId("5881b4bc745dbf49176e5cc6"),
"jId" : ObjectId("5881ab61745dbf49176e5cc5"),
"aId" : [
ObjectId("58819a25e381142fb0aa2214"),
ObjectId("5881b76e0e17c5500fe8284b")
ObjectId("5881b76e0e17c5500fe8284b")
],
"__v" : 0
}
Upvotes: 0
Views: 520
Reputation: 191799
From the MongoDB documentation:
The unique constraint applies to separate documents in the collection. That is, the unique index prevents separate documents from having the same value for the indexed key, but the index does not prevent a document from having multiple elements or embedded documents in an indexed array from having the same value
You need to handle unicity of the array yourself. Fortunately, $addToSet
operator cal help you keep the array values unique when you update applicants.
Upvotes: 1