尝试将新用户添加到数据库(MongoDB)时遇到此错误

时间:2020-03-27 07:47:14

标签: node.js mongodb

我正在尝试使用邮寄请求将用户保存到MongoDB数据库,如下所示,但出现错误TypeError:User不是一个函数。我不知道有什么问题。输出表明错误出现在“ const user = new User(req.body);”行上 postman output nodejs output

我的用户方案错误或导出方法错误。

const User = require("../models/user");

exports.signup = (req, res) => {
  const user = new User(req.body);
  user.save((err, user) => {
    if (err) {
      return res.status(400).json({
        err: "NOT able to save user in DB"
      });
    }
    res.json({
      name: user.name,
      email: user.email,
      id: user._id
    });
  });
};

exports.signout = (req, res) => {
  res.json({
    message: "User signout"
  });
};


//user schema
var mongoose = require("mongoose");
const crypto = require('crypto');
const uuidv1 = require('uuid/v1');


var userSchema = new mongoose.Schema({
    name:{
        type:String,
        required:true,
        maxlenght:32,
        trim: true
    },
    lastname:{
        type: String,
        maxlenght:32,
        trim: true
    },
    email:{
        type: String,
        trim: true,
        required: true,
        unique:true
    },
    userinfo:{
        type:String,
        trim:true
    },
    encry_password:{
        type:String,
        required: true,
    },
    salt:String,
    role:{
        type:Number,
        default:0,
    },
    purchases :{
        type:Array,
        default:[]
    }

} ,{ timestamps: true } );

userSchema.virtual("password")
    .set(function(password){
        this._password = password;
        this.salt = uuidv1();
        this.encry_password = this.securePassword(password);
    })
    .get(function(){
        return this._password;
    })

userSchema.methods = {
        authenticate: function(plainpassword){
            return this.securePassword(plainpassword) === this.encry_password;
    },

    securePassword: function (plainpassword){
        if(!plainpassword) return "";
        try {
            return crypto.createHmac('sha256',this.salt)
            .update(plainpassword)
            .digest('hex');
        } catch (err) {
            return "";
        }
    }
};




module.export = mongoose.model("User",userSchema)

1 个答案:

答案 0 :(得分:2)

这是代码的问题。

第1行:const user = new User(req.body);

第2行:user.save((err, user) => {

JS现在对user感到困惑,它是user的常量变量,而responseUserObj是保存操作的返回值。

因此,要消除此问题,请将save操作的返回值重命名为const user = new User(req.body); user.save((err, responseUserObj) => { 之类的其他值。因此,您上面的两行代码现在应该是

mapper.enable(CsvParser.Feature.WRAP_AS_ARRAY)

快乐的编码。