使用express.js无效帖子(意思是)

时间:2017-11-11 11:03:47

标签: node.js mongodb angular express

这是我的mongoDb连接

var mongoose = require('mongoose'); 
// Connection URL  
var db = 'mongodb://localhost:27017/employeeDetails';  
    // Use connect method to connect to the Server  
 mongoose.connect(db, function (error) {
    if (error) {
        console.log(error);
    }
});

var Schema = mongoose.Schema;
var Employee_Schema = new Schema({
    EmployeeName: String,
    Designation: String,
    Project: String,
    Skills:String
});

var Employee = mongoose.model('employees', Employee_Schema);

 module.exports=Employee;

这是我的api代码(express.js)

var express=require('express');
var router=express.Router();
var Employee=require('../database/dataFile');

router.get('/',function(req,resp,next){
    Employee.find({},function(err,docs){
        resp.send(docs);
    })
});

router.post('/create',function(req, resp, next){

    var employee_collection =Employee.collection(Employee);
    employee_collection.insert(req.body, function(err, doc) {
        if(err) throw err;
        console.log(doc);
        res.json(doc);
    });
});

 module.exports=router;

这是我的$ http.post

create(employee: Employee) {
    return this.http.post('http://localhost:4500/api/create', employee).map((response: Response) => response.json());
}

我总是得到

  

无法加载资源:服务器响应状态为500   (内部服务器错误)

仅供参考:$ http.get工作正常。它从MongoDb获取数据。以下命中了api中的get方法

getEmployeeList() {
    return this.http.get('http://localhost:4500/api');
}

请注意我从here举例说明 本教程没有Post功能,我正在尝试实现。

1 个答案:

答案 0 :(得分:1)

查询存在问题,如果要获取集合,请使用:

mongoose.getCollection(<collection name>), But here you are calling the collection function on a model object, not the mongoose one.

相反,我建议直接使用.create:

Employee.create(req.body, function(err,result){
   if(err){throw Error(err)}
   return res.json(result);
})