не могу вставить данные с помощью метода post в nodejs? - PullRequest
0 голосов
/ 04 сентября 2018

Я новичок в стеке Mean. Я не могу вставить какие-либо данные в mongoDB, используя метод post в nodejs. Здесь я добавил все соответствующие коды nodejs. , , , , , , , , , .

index.js

const express = require('express');
const bodyParser = require('body-parser');


const { mongoose } = require('./db.js');
var employeeController = require('../node/controller/employeeController');


var app = express();        //calling express
app.use(bodyParser.json());     //congigure express to send JSON data

var urlencoded_body_parser = bodyParser.urlencoded({
    extended: true
});

app.listen( 3000, () =>
    console.log("Server started successfully at Port 3000.")
);


app.use('/employees' , employeeController);
app.use(urlencoded_body_parser);

employee.js

    const mongoose = require('mongoose');

var Employee = mongoose.model('Employee',{
    name : String ,
    position :  String ,
    office : String,
    salery : Number
})

module.exports = { Employee };

employeeController.js

   const express = require('express')
var router = express.Router();
var ObjectId = require('mongoose').Types.ObjectId;

var { Employee } = require('../model/employee');

router.post('/', (req,res) => {
    var emp = new Employee({
        name : req.body.name,
        position : req.body.position,
        office : req.body.office,
        salary : req.body.salary
    });
    emp.save((err,doc) =>{
        if (!err){
            res.send(doc);
            console.log(doc);
        } else {
            console.log("Operation Failed : " + JSON.stringify(err,undefined,2));
        }
    })
});

router.put('/:id', (req,res)=> {
    if (!ObjectId.isValid(req.params.id)) {
        return res.status(400).send('No record with the given Id ${req.params.id}');
    }

    var emp = {
        name : String ,
        position :  String ,
        office : String,
        salery : Number
    };

    Employee.findByIdAndUpdate(req.params.id, { $set : emp },(err,docs) => {
        if (!err) {
            res.send(docs);
        } else {
            console.log('Error in Updating the Employee details' + JSON.stringify(err,undefined,2))
        }
    });
});


module.exports = route

когда я использую почтальон для вставки данных, он вставляет в базу данных только _id и _v. ни один из моих данных JSON. Скриншот почтальона

1 Ответ

0 голосов
/ 04 сентября 2018

Похоже, вы отправляете только необработанный текст на ваш сервер. Чтобы решить эту проблему, вам нужно указать тип вашего контента application/json.

В почтальоне это может выглядеть так: enter image description here

...