gpt4 book ai didi

javascript - Mongoose 重复索引

转载 作者:行者123 更新时间:2023-12-03 05:12:03 24 4
gpt4 key购买 nike

我正在使用数组来存储 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
}

最佳答案

来自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

您需要自己处理数组的唯一性。幸运的是,$addToSet运算符 cal 可帮助您在更新申请人时保持数组值的唯一性。

关于javascript - Mongoose 重复索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41767085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com