Mongoose save()不是一个函数

时间:2016-11-24 13:42:36

标签: javascript node.js mongodb mongoose

在我的app.js中,我需要我的模型

var User = require('./models/user');
app.post('/user/add', function(req,res,next){
  var newUser = new User();
  newUser.add(req.body.name, function(response){
    res.json(response);
  })
});

和我的模型(user.js)看起来像这样

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
    name: String
});
var User = module.exports = mongoose.model('user', userSchema);
module.exports.add = function(name,callback){
    User.save({name:name}).exec(callback);
}

但是我得到newUser.add错误不是函数?

3 个答案:

答案 0 :(得分:5)

如果要将实例方法添加到mongoose模型,则应使用instance methods语法:

var mongoose = require('mongoose');

var UserSchema = new mongoose.Schema({
    name: String
});

// Instance methods
UserSchema.methods.add = function(name, callback){
    this.name = name;
    return this.save(callback);
}

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

答案 1 :(得分:1)

可以使用类似

的方法关键字添加方法
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
    name: String
});

userSchema.methods.add = function(name,callback){    
    User.save({name:name}).exec(callback); // not checking logic
}
var User = module.exports = mongoose.model('user', userSchema);

答案 2 :(得分:1)

您可以按照以下方式执行此操作:

var mongoose = require('mongoose');
var Schema = Mongoose.Schema;

//schema is declared here
var userSchema = new Schema({
    name: String
});

var user = Mongoose.model('User', UserSchema);

//here we are assigning new data to user collection
//this record will not be saved here
//it will only check the schema is matching or not
//if record is matching to schema then it will assign '_id' to that record
var userRec = new user({"name":"Jessie Emerson"});

userRec.save(function(error, userDoc) {

    //this is the callback function
});

如果您需要更多说明,请对此答案发表评论。 : - )