Mongoose - 如何从唯一数组中删除所有元素?

时间:2018-03-30 14:23:27

标签: mongodb mongoose mean-stack

我的Schema中有一个唯一的数组:

requests: {
    type: [
      {
        type: Schema.Types.ObjectId,
        ref: "user",
        unique: true,
        required: false
      }
    ],
    validate: [memberLimit, "{PATH} overflow"]
  }

memberLimit函数:

function memberLimit(val) {
  return val.length <= 6;
}

要删除数组中的所有元素,我尝试了:

team.requests = [];

产生错误:

{ MongoError: E11000 duplicate key error index: heroku_sx6rhpl8.teams.$requests_
1 dup key: { : undefined }
    at Function.MongoError.create (H:\Projects\xyz\node_modules\mongoose\node_
modules\mongodb-core\lib\error.js:45:10)
    at toError (H:\Projects\xyz\node_modules\mongoose\node_modules\mongodb\lib
\utils.js:149:22)
    at H:\Projects\xyz\node_modules\mongoose\node_modules\mongodb\lib\collecti
on.js:1035:39
    at H:\Projects\xyz\node_modules\mongoose\node_modules\mongodb-core\lib\con
nection\pool.js:541:18
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)
  name: 'MongoError',
  message: 'E11000 duplicate key error index: heroku_sx6rhpl8.teams.$requests_1
dup key: { : undefined }',
  driver: true,
  index: 0,
  code: 11000,
  errmsg: 'E11000 duplicate key error index: heroku_sx6rhpl8.teams.$requests_1 d
up key: { : undefined }' }

我做错了什么?

1 个答案:

答案 0 :(得分:0)

尝试确认typeOf teams.requests是一个数组。如果那是真的,那么尝试清除数据库中的所有索引并重新运行代码。希望有所帮助。