Nodejs Expressjs和MongoDb

时间:2018-05-06 12:42:11

标签: node.js express

我创建了两个模型,oders.js和users.js以及两个路由index.js和users.js,我的目的只是将users.js文件中的数据保存到mongodb(Userschema),但是没有工作post方法users.js文件没有加载,请检查users.js模型并让我知道是否有任何问题,如果我们在节点中创建多个模型,那么我们是否需要在每个模型中创建连接? 这是模型的代码。 users.js

var mongoose=require('mongoose');
mongoose.connect('mongodb://localhost/test');`enter code here`
var conn=mongoose.connection;

var UserSchema=mongoose.Schema({
name:String,
    department:String,
    designation:String

});

var UserModel=mongoose.model('users',UserSchema);

module.exports=UserModel;

这是Order.js文件

        var mongoose=require("mongoose");

mongoose.connect('mongodb://localhost/test');

var conn=mongoose.connection;

var OrderSchema=mongoose.Schema({
    item:String,
    price:Number,
    quamtity:Number,
    total:Number

});

var OrderModel=mongoose.model('orders',OrderSchema);

module.exports=OrderModel;

这是路线的代码 Users.js

    var express = require('express');

var router = express.Router();

var Usersmodel=require('../models/users');
var query=Usersmodel.find({});`enter code here

router.get('/showusers', function(req, res, next) {

  query.exec(function(err ,doc){
    if(err)throw err;
    res.render('users',{title:"Show all users",rows:doc});

  });

});

router.post('/showusers',function(req , res ,next){



  var newrec=new Users({
    name:req.body.name,
    department:req.body.department,
    designation:req.body.designation

  })

  newrec.save(function(err,doc){
    if(err)throw err;
    query.exec(function(err,doc){
      if(err)throw err;
      res.render('users',{rows:doc});
    });

  });

});

module.exports = router;

订单路由工作正常,但users.js post方法显示500错误未加载

1 个答案:

答案 0 :(得分:0)

首先,请从模型文件中删除连接。由于多个连接,它会产生问题。你去吧

var express = require('express');

var router = express.Router();

var Usersmodel = require('../models/users');
//var query=Usersmodel.find({});`enter code here

router.get('/showusers', function (req, res, next) {

    Usersmodel.find({}, function (err, doc) {
        if (err) throw err;
        res.render('users', {
            title: "Show all users",
            rows: doc
        });

    });

});

router.post('/showusers', function (req, res, next) {
    Usersmodel.create({
        name: req.body.name,
        department: req.body.department,
        designation: req.body.designation
    }, function (err, response) {
        Usersmodel.find({}, function (err, doc) {
            if (err) throw err;
            res.render('users', {
                title: "Show all users",
                rows: doc
            });

        });
    });
});