【问题标题】:.save() is not a Function Mongoose.save() 不是函数 Mongoose
【发布时间】:2016-05-30 19:08:37
【问题描述】:

我不断收到 newUser.save() 不是函数的问题。这是我之前用过的猫鼬函数。我正确要求猫鼬,但不确定为什么会发生此错误。欢迎任何帮助。

我得到的错误是TypeError: newUser.save is not a function

模型文件夹中的我的 user.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);
  });
}

Routes 文件夹中的我的 users.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;

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

    你这里有一些问题。

    类似这样的东西(用户引用您的架构):

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

    应该会更好。您现在不是传递一个新对象(显然不包含 save 方法),而是从架构中创建一个新对象,设置参数,然后保存它。

    然后你还必须更改为:

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

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

    【讨论】:

    • 我会将钩子放在哪个文件中?
    • 您的架构。 user.js 在你的情况下。顺便说一下,它可能是 UserSchema.pre 而不是 User.pre。
    • 我想出了一个不同的方法让它工作,这更简单,谢谢你的帮助。我只需要在调用 createUser 之前创建 newUser 而不是一次完成所有操作
    【解决方案2】:

    createUser() 是一个常规函数,您将常规对象(作为 newUser 参数)传递给:

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

    常规对象没有.save 方法。

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

    【讨论】:

    猜你喜欢
    • 2022-11-15
    • 1970-01-01
    • 2016-12-08
    • 2016-02-05
    • 1970-01-01
    • 2021-07-14
    • 2021-01-08
    • 1970-01-01
    • 2017-01-16
    相关资源
    最近更新 更多