Mongoose:如何防止MongoDB在数据库中保存重复的电子邮件logging
我想要使关键邮件唯一的整个集合,但我不能得到这个工作,这里是我的服务器代码。
// 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}
但它不工作,并显示下面的错误。
名称:'MongoError',
消息:'E11000重复密钥错误集合:hutreservationsystem.users
索引:_Email_1 dup键:{:null}',
司机:真,
代码:11000,
索引:0,
errmsg:'E11000重复键错误集合:hutreservationsystem.users索引:_Email_1 dup键:{:null}',
getOperation:[Function],
toJSON:[function],
toString:[Function]}
asynchronous定制validation器
var userSchema = new mongoose.Schema({ password: String, email: { type: String, lowercase: true, required: true, validate: { isAsync: true, validator: function(value, isValid) { const self = this; return self.constructor.findOne({ email: value }) .exec(function(err, user){ if(err){ throw err; } else if(user) { if(self.id === user.id) { // if finding and saving then it's valid even for existing email return isValid(true); } return isValid(false); } else{ return isValid(true); } }) }, message: 'The email address is already taken!' }, } });
您可能想要将validation器代码更改为es6。
我实现了下面的代码来查看是否有什么错误:
var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var express = require('express'); var http = require('http'); var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); var Schema = mongoose.Schema; mongoose.connect('mongodb://localhost/test'); // Create a schema var userSchema = new mongoose.Schema({ email: { type: String, required: true, unique: true}, password: String }); var userModel = mongoose.model("user", userSchema); app.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); } }) }); http.createServer(app).listen(3000, function(){ console.log('Express server listening on port 3000'); });
而且我确信在我的本地MongoDB数据库中不存在users
名的存在。 此外,我使用邮递员发送API请求到我的服务器在http://localhost:3000
。 似乎没有问题,因为我继续添加具有不同电子邮件值的用户。 当我input重复值的电子邮件时,我只收到以下错误
{ "code": 11000, "index": 0, "errmsg": "E11000 duplicate key error collection: test.users index: email_1 dup key: { : \"hot@mail.com\" }", "op": { "email": "hot@mail.com", "password": "1234567", "_id": "5919a3428c13271f6f6eab0f", "__v": 0 } }
这些是我发送的JSON请求:
{"_user": {"email": "hot@mail.com", "password": "1234"}} {"_user": {"email": "sammy@mail.com", "password": "1234"}} {"_user": {"email": "tommy@mail.com", "password": "1234"}} {"_user": {"email": "tommy@mail.ae", "password": "1234567"}} {"_user": {"email": "hot@mail.com", "password": "1234567"}}
上面提到的错误是在最后一次请求时发回的,因为电子邮件hot@mail.com
被重复。 如果您查看链接http://mongoosejs.com/docs/api.html#schematype_SchemaType-unique ,您将看到只有在input的电子邮件不唯一时才会发送E11000错误。 此外,您的电子邮件不能是空string或不存在,因为这违反了必需的属性。
- node-mongodb-native MongoClient意外closures连接
- node.js mongodb如何连接到mongo服务器的replicaset
- (node:6868) DeprecationWarning:`node –inspect –debug-brk`已被弃用
- find插入mongoose的最新子文件的id
- mongoose – 保存用户_id到不同的模式更改ID
- 如何在不使用_id的情况下返回数据当我在mongoose中使用findByIdAndUpdate?
- mongoose – 使用单个集合的多个模式
- Bitnami MEANstack:找不到模块'mongoose'
- angular.js – TypeError:无法读取未定义的属性'then'