gpt4 book ai didi

node.js - Mongoose :如何防止mongodb在数据库中保存重复的电子邮件记录

转载 作者:可可西里 更新时间:2023-11-01 09:09:17 26 4
gpt4 key购买 nike

我想让关键电子邮件在该集合中唯一,但我无法正常工作,这是我的服务器代码。

// Create a schema
var userSchema = new mongoose.Schema({
email: { type: String, required: true},
password: String
});

var userModel = mongoose.model("user", userSchema);

router.post('/postuser', (req, res) => {
console.log('Requested data to server: ' + JSON.stringify(req.body._user));
var user = new userModel({
email: req.body._user.email,
password: req.body._user.password
});
// user.isNew = false;
user.save((err, data) => {
console.log('Analyzing Data...');
if(data) {
console.log('Your data has been successfully saved.');
res.json(data);
}
else {
console.log('Something went wrong while saving data.');
console.log(err);
res.send(err);
}

})
});

注意:我也尝试了 email: { type: String, required: true, unique: true} 但它不起作用并显示以下错误。

name: 'MongoError',

message: 'E11000 duplicate key error collection: hutreservationsystem.users

index: _Email_1 dup key: { : null }',

driver: true,

code: 11000,

index: 0,

errmsg: 'E11000 duplicate key error collection: hutreservationsystem.users index: _Email_1 dup key: { : null }',

getOperation: [Function],

toJSON: [Function],

toString: [Function] }

最佳答案

使用此工具的简短回答 mongoose-unique-validator

npm install --save mongoose-unique-validator

在你的模型中

var mongoose = require('mongoose')
var uniqueValidator = require('mongoose-unique-validator')
var userSchema = new mongoose.Schema({
email: { type: String, required: true, unique: true},
password: String
});

userSchema.plugin(uniqueValidator)
var userModel = mongoose.model("user", userSchema);

就是这样! (注意唯一性:true)

现在,您的收藏中没有电子邮件重复。

奖金! : 你可以访问 err

.catch(err => console.log(err))

所以在你的例子中

// user.isNew = false;
user.save((err, data) => {
console.log('Analyzing Data...');
if(data) {
console.log('Your data has been successfully saved.');
res.json(data);
}
else {
console.log('Something went wrong while saving data.');
console.log(err);
res.send(err);
}

访问错误>>所以你可以 res.send(err.message) >> '验证失败'

{
message: 'Validation failed',
name: 'ValidationError',
errors: {
email: {
message: 'Error, expected `email` to be unique. Value: `example@gmail.com`',
name: 'ValidatorError',
kind: 'unique',
path: 'email',
value: 'example@gmail.com'
}
}
}

关于node.js - Mongoose :如何防止mongodb在数据库中保存重复的电子邮件记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43962430/

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