mongoose得到`TypeError:user.save不是函数` - 出了什么问题

时间:2016-11-01 06:59:16

标签: node.js mongodb mongoose

我正在尝试将用户数据发布到mongodb,但我收到错误消息:

`TypeError:user.save不是函数' - 如何解决这个问题?

这是我的代码:

var

    express     = require('express'),
    app         = express(),
    bodyParser  = require('body-parser'),
    mongoose    = require('mongoose'),
    PORT        = process.env.PORT || 8080;



//connect to db 

mongoose.connect('mongodb://3gwebtrain:admsin@ds147975.mlab.com:47975/family');

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


app.get('/', function( req, res ) {

    res.json({message:'works'})

});


var Schema = mongoose.Schema;

var User = new Schema({

    name:String,
    username:{type:String, required:true, index:{unique:true}},
    password:{type:String, required:true, select:false}

})


var apiRouter = express.Router();


apiRouter
    .get('/users', function( req, res ){

        res.send( "yet to get users!");

    })
    .post('/users', function( req, res ) {

        var user = User;

        user.name = req.body.name;
        user.username = req.body.username;
        user.password = req.body.password;

        user.save(function(err) {

            if( err ) {

                console.log( err ); //TypeError: user.save is not a function

            }

            res.send("user created!");

        })

    })


app.use('/api', apiRouter);


app.listen( PORT );
console.log( 'app listens at ' + PORT );

3 个答案:

答案 0 :(得分:11)

首先从Schema创建模型:

 var UserModel = mongoose.model('User', User);

然后从用户模型中创建对象

 var user = new UserModel(req.body)

然后致电

 user.save(function(){})

检查文档    http://mongoosejs.com/docs/api.html#model_Model-save

答案 1 :(得分:1)

您还需要定义模型,将模式定义更改为:

var UserSchema = new mongoose.Schema({
name:String,
username:{type:String, required:true, index:{unique:true}},
password:{type:String, required:true, select:false}
})
var User = mongoose.model('User', UserSchema);

然后你应该好好去:)

答案 2 :(得分:0)

使用

let user = new User;

错误已解决