用户不是构造函数

时间:2018-06-10 16:56:53

标签: mongodb mongoose

我在尝试将新文档添加到我的数据库时收到错误:User is not a constructor。在我使用mongoose.model而不使用Schema方法之前,它工作得很好,但我必须添加验证器,它需要这种语法,从那以后我就无法使其工作

代码:

var UserSchema = mongoose.Schema({
    username: { type: String, required: true, unique: true },
    email: { type: String, index: true, unique: true, required: true },
    password: { type: String, required: true }
});

UserSchema.plugin(uniqueValidator);

let User = mongoose.model("user", UserSchema);
module.exports = User;


router.post('/', (req, res) => {


    var user = new User({
        username: req.body.username,
        email: req.body.email,
        password: req.body.password          
    });

    // save the user
    user.save(function (err) {
        if (err) {
            console.log('Error in Saving user: ' + err);
            throw err;
        }
        console.log('User Registration succesful');
        // return done(null, userData);
        res.status(200).send({user: user})
    });

});

2 个答案:

答案 0 :(得分:0)

mongoose.Schema是构造函数,因此您需要使用" new":

来调用它
var UserSchema = new mongoose.Schema({
    username: { type: String, required: true, unique: true },
    email: { type: String, index: true, unique: true, required: true },
    password: { type: String, required: true }
});

答案 1 :(得分:0)

好的我修正了我的问题,而不是

module.exports = User;

我必须这样做:

module.exports = {User};