我正在使用Express,MongoDB和Mongoose編寫API。我以某種方式能夠使用相同的電子郵件創建多個用戶。但是,我不能使用相同的電子郵件地址創建其他用戶。我在我的用戶架構中有電子郵件unique: true
,但這不能按預期工作。儘管電子郵件設置爲在Mongoose中唯一,但可以使用同一電子郵件創建多個用戶
這裏是我的用戶模式:
var UserSchema = new Schema({
fullName: { type: String, required: [true, 'Full name is required.'] },
emailAddress: {
type: String, required: true, unique: true,
validate: {
validator: function (value) {
// check for correct email format
return /^[a-zA-Z0-9.!#$%&’*+\/=?^_`{|}~-][email protected][a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(value)
},
message: `Please enter a valid email address!`
}
},
password: { type: String, required: true }
});
我的用戶身份驗證方法:
UserSchema.statics.authenticate = function (email, password, callback) {
User.findOne({ emailAddress: email })
.exec(function (err, user) {
if (err) {
return callback(err);
} else if (!user) {
var error = new Error('User not found');
error.status = 401;
return callback(error);
}
bcrypt.compare(password, user.password, function (error, user) {
if (user) {
return callback(null, user);
} else {
return callback();
}
});
});
}
我的預存鉤散列密碼:
UserSchema.pre('save', function (next) {
var user = this;
bcrypt.hash(user.password, 10, function (err, hash) {
if (err) {
return next(err);
}
user.password = hash;
next();
});
});
最後,我的用戶創建路線:
router.post('/', function (req, res, next) {
if (req.body.fullName &&
req.body.emailAddress &&
req.body.password &&
req.body.confirmPassword) {
if (req.body.password != req.body.confirmPassword) {
var err = new Error('Passwords do not match!');
err.status = 400;
return next(err);
}
// object with form input
var userData = {
fullName: req.body.fullName,
emailAddress: req.body.emailAddress,
password: req.body.password
};
// schema's 'create' method to insert document into Mongo
User.create(userData, function (error, user) {
if (error) {
var err = new Error('Please enter a valid email.');
err.status = 400;
return next(err);
} else {
// set location header to '/', return no content
res.status(201);
res.location('/');
req.session.userId = user._id;
return res.json(user);
}
});
} else {
var err = new Error('All fields required.');
err.status = 400;
return next(err);
}
});
您的用戶文檔是否分配了一個帶有ObjectId的_id字段? – wscourge
@wscourge是的,下面是返回的結果,用'_id'自動生成(不確定'ObjectId'是什麼意思,但是我相信'_id'字段的值就是你要找的。 '''{ 「__v」:0, 「全名」: 「約翰·史密斯」, 「EMAILADDRESS」: 「[email protected]」, 「密碼」:「$ 2A $ 10 $ P.VQVungzx9wMyKrI7nOu.1Sh5ikfB1SYUpzi /hFqqu.Ae4wM4c2。「, 」_id「:」59e657e08d643599fe1de35a「 }''' – wellowlbe
如果您處於測試環境中,您可以嘗試關閉應用程序,插入'mongoose.set('debug',true)'right在mongoose連接語句(用於詳細調試)之後,關閉mongod,然後重新啓動mongod和你的應用程序。你可能會遇到這個問題,因爲索引在創建之後還沒有被創建設置獨特的真實。請參閱[這裏](http://mongoosejs.com/docs/guide.html#indexes)瞭解更多信息。重新啓動應用程序應創建索引,並在此之後使用唯一性。 – MikaS