我和Mongoose发生了一个奇怪的错误。当用户注册时,他们会提供他们所属组织的名称。以前,这需要是独一无二的。我的架构是:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Organisation = new mongoose.Schema({
name: {
type: String,
required: true,
unique: true
},
createdById: {
type: Schema.Types.ObjectId,
ref: 'User'
},
createdOn: {
type: Date,
"default": Date.now
},
availableUntil: {
type: Date
}
});
Organisation.path('name').validate(function(value, done) {
var self = this;
if (!self.isNew) {
return done(true);
} else {
//mongoose.models['Organisation'] or self.model('Organisation')
mongoose.models['Organisation'].count({
name: value
}, function(err, count) {
if (err) {
return done(err);
}
return done(!count)
});
}
}, "This email already exists");
mongoose.model('Organisation', Organisation);
但是现在没关系,组织名称不需要是唯一的。所以我改为:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Organisation = new mongoose.Schema({
name: {
type: String,
required: true
},
createdById: {
type: Schema.Types.ObjectId,
ref: 'User'
},
createdOn: {
type: Date,
"default": Date.now
},
availableUntil: {
type: Date
}
});
mongoose.model('Organisation', Organisation);
请注意unique: true
已删除的方式。
我重新启动了服务器,但奇怪的是,我仍然收到错误:
name: 'MongoError',
message: 'E11000 duplicate key error index: redmatter.organisations.$name_1 dup key: { : "delete me" }',
driver: true,
code: 11000,
index: 0,
errmsg: 'E11000 duplicate key error index: redmatter.organisations.$name_1 dup key: { : "delete me" }',
getOperation: [Function],
toJSON: [Function],
toString: [Function] }
这怎么可能?当我不在乎名称是否不唯一时,为什么会出现重复键错误?