.save()不是一个函数Mongoose

时间:2022-12-31 15:48:13

I keep getting an issue that newUser.save() is not a function. This is a mongoose function that I have used before. I required mongoose correctly and am unsure of why this error is occurring. Any help is welcomed.

我不断地发现newUser.save()不是函数。这是我以前用过的一个mongoose函数。我要求mongoose正确,但我不确定为什么会出现这种错误。任何帮助表示欢迎。

The error I am getting is TypeError: newUser.save is not a function

我得到的错误是TypeError: newUser。save不是函数

My user.js inside the Models Folder

我的用户。model文件夹中的js

var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
  name: String,
  email: String,
  password: String,
  info: String
});

var User = module.exports = mongoose.model('User', UserSchema);

module.exports.createUser = function(newUser, callback){
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(newUser.password, salt, function(err, hash) {
            newUser.password = hash;
            newUser.save(callback);
        });
    });
}

module.exports.getUserByUsername = function(username, callback){
    User.findOne({username : username}, callback);
}

module.exports.getUserById = function(id, callback){
    User.findById(id, callback);
}

module.exports.checkPassword = function(candidatePass, hash, callback){
  bcrypt.compare(candidatePass, hash, function(err, res) {
    if(err) throw err;
    callback(null, res);
  });
}

My users.js inside the Routes Folder

我的用户。route文件夹中的js

//Mongoose Setup
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect("MY_DB");
var path = require('path');
var appDir = path.dirname(require.main.filename);
var bodyParser = require('body-parser')
var User = require('../models/user.js');

//Express Setup
var express = require('express');
var router = express.Router();
var app = express();
var expressValidator = require("express-validator");

app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressValidator());
app.use(bodyParser.json());

//Routes
router.get('/register', function(req, res){
  res.sendFile(appDir + "/views/register.html");
})

router.post('/register', function(req, res) {
  req.check('name', 'Name must be Filled in').notEmpty();
  req.check('email', 'Email must be Filled in').notEmpty();
  req.check('email', "Invalid Email").isEmail();
  req.check('password', 'Password Field must be Filled in').notEmpty();
  req.check('password', 'Passwords do not Match').equals(req.body.password2)
  var errors = req.validationErrors();
  if(errors) res.send(errors)
  else{ User.createUser({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
    info: req.body.user_bio
  }, function(){
    console.log('User Created');
  })
}
})

//Exports
module.exports = router;

2 个解决方案

#1


4  

createUser() is a regular function that you're passing a regular object (as the newUser argument) to:

createUser()是一个常规的函数,您正在通过一个常规对象(作为newUser参数):

User.createUser({
  name : req.body.name,
  ...
}, ...);

Regular objects don't have a .save method.

常规对象没有.save方法。

What you probably want is to create a static method as part of your model. That would allow you to call User.createUser like you are doing now (notice how static methods are created on the schema, not the model. Also, you have to define static methods before creating a model from the schema)

您可能希望创建一个静态方法作为模型的一部分。这将允许您调用User。像您现在正在做的那样创建一个createUser(请注意静态方法是如何在模式上创建的,而不是在模型上。此外,您必须在从模式创建模型之前定义静态方法)

#2


3  

You have got some things wrong here.

你这里有些地方不对劲。

Something like this (User refers to your schema):

类似这样(用户参考您的模式):

var user = new User();
user.name = req.body.name;
user.email = req.body.email;
user.password = req.body.password;
user.info = req.body.user_bio;
user.save().then(function(err, result) {
    console.log('User Created');
});

should work better. Instead of passing a new object (which obviously doesn't contain the save method), you are now creating a new object from the schema, setting the parameters, and then save it.

应该更好的工作。而不是传递一个新对象(显然它不包含save方法),而是从模式创建一个新对象,设置参数,然后保存它。

You then also have to change to this:

然后你还必须改变这一点:

User.pre('save', function(next) {
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(this.password, salt, function(err, hash) {
            this.password = hash;
            next();
        });
    });
}

This is a hook, which is called every time before the user gets saved.

这是一个钩子,每次用户保存之前都会调用它。

#1


4  

createUser() is a regular function that you're passing a regular object (as the newUser argument) to:

createUser()是一个常规的函数,您正在通过一个常规对象(作为newUser参数):

User.createUser({
  name : req.body.name,
  ...
}, ...);

Regular objects don't have a .save method.

常规对象没有.save方法。

What you probably want is to create a static method as part of your model. That would allow you to call User.createUser like you are doing now (notice how static methods are created on the schema, not the model. Also, you have to define static methods before creating a model from the schema)

您可能希望创建一个静态方法作为模型的一部分。这将允许您调用User。像您现在正在做的那样创建一个createUser(请注意静态方法是如何在模式上创建的,而不是在模型上。此外,您必须在从模式创建模型之前定义静态方法)

#2


3  

You have got some things wrong here.

你这里有些地方不对劲。

Something like this (User refers to your schema):

类似这样(用户参考您的模式):

var user = new User();
user.name = req.body.name;
user.email = req.body.email;
user.password = req.body.password;
user.info = req.body.user_bio;
user.save().then(function(err, result) {
    console.log('User Created');
});

should work better. Instead of passing a new object (which obviously doesn't contain the save method), you are now creating a new object from the schema, setting the parameters, and then save it.

应该更好的工作。而不是传递一个新对象(显然它不包含save方法),而是从模式创建一个新对象,设置参数,然后保存它。

You then also have to change to this:

然后你还必须改变这一点:

User.pre('save', function(next) {
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(this.password, salt, function(err, hash) {
            this.password = hash;
            next();
        });
    });
}

This is a hook, which is called every time before the user gets saved.

这是一个钩子,每次用户保存之前都会调用它。