-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathunique.js
37 lines (30 loc) · 804 Bytes
/
unique.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const mongooseErrorHandler = require('../');
mongoose.Promise = Promise;
mongoose.connect('mongodb://localhost/example', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.plugin(uniqueValidator);
const schema = new mongoose.Schema({
name: {
type: String,
unique: true,
},
});
const model = mongoose.model('person', schema);
const object = new model({ name: 'a' });
object.save(function (err, doc) {
if (err) {
const error = mongooseErrorHandler(err);
console.log(error);
/**
* Error [MongooseValidatorError]: "name" already exists
* name: 'MongooseValidatorError',
* path: 'name',
* kind: 'unique',
* value: "a"
*/
}
});