保存功能在expressjs mongoose

时间:2016-04-23 14:04:18

标签: node.js mongodb express mongoose

我正在尝试将表单数据保存到mongodb数据库中。当我尝试使用.Find方法时,它返回来自users集合的数据。但是当我尝试保存数据时,它会显示错误消息。 .Save方法也应该使用相同的Schema,但事实并非如此。这是我的代码:

var express= require('express');
var mongoose = require('mongoose');
var path = require('path');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');    
var app= express();
/* set view folder and view engine */
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');    
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());    
/* database connection */
mongoose.connect('mongodb://localhost:27017/expresstest', function (err) {
    if (err) {
        console.log(err);
    }   
});

/* define user schema */
var Schema = mongoose.Schema;
var UserSchema = new Schema({name:String, password: String, phone: String, created: Date});
var User= mongoose.model('users',UserSchema);
/* open new user form */
app.get('/user', function(req, res){
    res.render('user');
});

/* save user */
app.post('/user', function(req, res){
    User.save({
        name: req.body.name, 
        password: req.body.password, 
        phone: req.body.phone
    }, function( error, docs) {
        res.redirect('/')
    });
});    
app.listen(3000, function(){
    console.log('express app is running on port 3000.');
});

1 个答案:

答案 0 :(得分:4)

你正在调用错误的函数。这是功能签名。在User的对象上调用Save,而在模型User上调用create。这是一个例子:

var Tank = mongoose.model('Tank', yourSchema);

var small = new Tank({ size: 'small' });
small.save(function (err) {
  if (err) return handleError(err);
  // saved!
});

// or

Tank.create({ size: 'small' }, function (err, small) {
  if (err) return handleError(err);
  // saved!
});

详细了解here