Reputation: 355
I'm new to Node.js so I can't understand what I need to add, to make the default example from mongoose-unique-validator
work. Here it is:
const mongoose = require('mongoose'),
uniqueValidator = require('mongoose-unique-validator'),
userSchema = mongoose.Schema({
username: { type: String, required: true, unique: true },
room: { type: String, required: true },
});
userSchema.plugin(uniqueValidator);
const user = new User({ username: 'JohnSmith', room: 'asd');
user.save(function (err) {
console.log(err);
});
The part with the user is not working, because of ReferenceError: User is not defined
.
As far as I understand, the user
part is the part that the library user should define, but I don't know what should be in there to make it work.
TL; DR:
I just want to make an example work. Thanks.
Update:
Ok, so I've added this line of code:
const User = mongoose.model('Model', userSchema);
and it does not trows an error anymore. But it does not notify that username
is not unique. It does not work yet. I want to check a valid username for the room. And that's all.
Upvotes: 0
Views: 435
Reputation: 2350
you didn't define your model collection ("USER") try this:
const mongoose = require('mongoose'),
uniqueValidator = require('mongoose-unique-validator'),
userSchema = mongoose.Schema({
username: { type: String, required: true, unique: true },
room: { type: String, required: true },
});
userSchema.plugin(uniqueValidator);
module.exports.User = mongoose.model('User', UserSchema);
then :
const user = new User({ username: 'JohnSmith', room: 'asd');
user.save(function (err) {
console.log(err);
})
Upvotes: 1