javascript - Mongoose 重复索引

标签 javascript node.js mongoose

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

相关文章:

javascript - 热衷于为 React 中的每个元素制作唯一的 NavLink?

javascript - 用于填充 javascript 关联数组的有效语法

ajax - node express 服务器不响应 ajax

node.js - Node Sequelize Postgres - BulkCreate 忽略自定义字段的重复值

javascript - 在 asp.net mvc 应用程序中动态更改样式

java - 是否可以选择在 onSubmit 中发送的表单上的项目?

node.js - 如何在 Typescript 中将属性重写为不可为空

node.js - 用于算术运算的 MongoDB 聚合 - 子文档字段

javascript - 如何与node.js同时支持api和web界面数据交互?

node.js - NodeJS 崩溃 : Mongoose findById() does NOT throw error when document is NOT found