我正在使用数组来存储 ObjectId,但即使是重复的 Id 也被 已保存
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);
在数据库中,aId ObjectId 按顺序存储为 0,1,2,3...... 但即使使用索引,id 也会重复保存,
{
"_id" : ObjectId("5881b4bc745dbf49176e5cc6"),
"jId" : ObjectId("5881ab61745dbf49176e5cc5"),
"aId" : [
ObjectId("58819a25e381142fb0aa2214"),
ObjectId("5881b76e0e17c5500fe8284b")
ObjectId("5881b76e0e17c5500fe8284b")
],
"__v" : 0
}
最佳答案
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
您需要自己处理数组的唯一性。幸运的是,$addToSet
运算符 cal 可帮助您在更新申请人时保持数组值的唯一性。
关于javascript - Mongoose 重复索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41767085/