提问者:小点点

mongoose-unique-validator ReferenceError:未定义用户


我是Node.js的新手,所以我不明白要使mongoose-unique-validator中的默认示例工作,需要添加什么。 这是:

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);
});

由于ReferenceError:user is not defined,带有user的部件无法工作。 据我所知,user部分是库用户应该定义的部分,但我不知道应该在其中包含什么以使其工作。

TL; 博士:

我只是想做个例子。 谢了。

更新:

好的,我添加了这行代码:

const User = mongoose.model('Model', userSchema);

而且它不会再犯错误了。 但它不会通知username不是唯一的。 现在还不行。 我要检查房间的有效用户名。 就这样。


共1个答案

匿名用户

您没有定义模型集合(“用户”),请尝试如下所示:

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);

那么:

const user = new User({ username: 'JohnSmith', room: 'asd');
user.save(function (err) {
    console.log(err);
})