TheCoderGuy
TheCoderGuy

Reputation: 863

Node.js POST request has data but in mongoDB I see only the id not the data

enter image description here As you can see in the picture it saves nothing. The POST request is working, but the data which I am sending to Backend it is saving only new Object with ID but not the data which I have giving.

I do not have any error or something the status is OK. I am testing this with Postman.

I will add some code.

This is the model.

const mongoose = require("mongoose");

const dataModelScheme = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    personalData: {
        _id: mongoose.Schema.Types.ObjectId,
        title: String,
        firstName: String,
        lastName: String,
        email: String,
        birthday: String,
        telephone: Number,
        driveLicense: String,
        status: Number,
        employmentType: String,
        job: String,
    },
    skills: {
        _id: mongoose.Schema.Types.ObjectId,
        name: String,
        startDate: Number,
        endDate: Number,
        description: String,
    },
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    },
});
module.exports = mongoose.model('ModelSchema', dataModelScheme);

module.exports = {
    async store(req, res) {
        const modelData = new ModelData({
            _id: new mongoose.Types.ObjectId(),
            personalData: {
                _id: new mongoose.Types.ObjectId(),
                firstName: req.body.firstName,
            },
            skills: {
                _id: new mongoose.Types.ObjectId(),
                name: req.body.name,
            },
        });
        modelData.save().then(result => {
            res.status(201).json({
                message: "Handling POST request to modelData",
                modelData: result
            });
        }).catch(error => {
            res.status(500).json({error: error});
        });
    },
}

I am trying with Postman like this.

POST -> http://localhost:5000/data

const express = require('express');
const routes = express.Router();
routes.post("/data", ModelDataController.store);
module.exports = routes;

This is the JSON file which I am trying to send with request.

{
    "personalData": {
        "firstName": "Max"
    },
    "skillks": {
        "name": "Muster"
            }

}

Upvotes: 0

Views: 767

Answers (1)

Edeph
Edeph

Reputation: 772

You do req.body.firstName instead of req.body.personalData.firstName. Same for the name property.

What you put in Postman under raw is going to correspond to your req.body.

Upvotes: 1

Related Questions