0

i am new in node.js. I'm trying to store three different objects in collection in mongodb using node.js.

index.js

var mongoose = require('mongoose');
var bodyparser = require('body-parser');
var app = express();
var control = require('./controllers/controller');
var port = 3200;

mongoose.connect(
    'mongodb://localhost:27017/create-company',
    {useNewUrlParser: true},
    err => {
        if(err) throw err;
        console.log('connection successfully');
    }
)
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended: true}));
app.use('/api', control);

app.listen(port, function(){
    console.log('start your server on: ', port);
});

model.js

var mongoose = require('mongoose');

var CompanySchema = new mongoose.Schema({
    companyname: String,
    founder: String,
    contact: String,
    location: String
});
var company = mongoose.model("company", CompanySchema); 

var BranchSchema = new mongoose.Schema({
    branchname: String,
    branchmanger: String,
    contact: String,
    location: String  
});
var branch = mongoose.model('branch', BranchSchema);

var UserSchema = new mongoose.Schema({[enter image description here][1]
    username: String,
    userrole: String,
    age: Number
});
var user = mongoose.model('user', UserSchema);

module.exports = {
    company: company,
    branch: branch,
    user: user
}

controller.js

var express = require('express');
var router = express.Router();
var company = require('../models/model');

router.post('/create_company', function (req, res) {
    var new_company = new company.company(req.body);
    var new_branch = new company.branch(req.body);
    var new_user = new company.user(req.body);

   new_company.save(function (err, data) {
        if (err) 
        res.send(data);
        console.log(data);
    });

    new_branch.save(function (err, data) {
        if (err) 
        res.send(data);
        console.log(data);
    });


    new_user.save(function (err, data) {
        if (err)
        res.send(data);
        console.log(data);
    });

});

i am pass data to postman like this:

[{ "companyname": "stack", "founder": "alex", "contact": "1234567890", "location": "in" }, { "branchname": "am", "branchmanager": "abc", "contact": "8754216523", "location": "inn" }, { "username": "xyz", "userrole": "admin", "age": "23" }]

enter image description here

1 Answer 1

0

There are three problems here:

You are attempting to create a new document by passing the entire body to the constructor. You need to pass the correct array element to it's respective constructor.

var new_company = new company.company(req.body[0]);
var new_branch = new company.branch(req.body[1]);
var new_user = new company.user(req.body[2]);

You are attempting to send a response more than once. You need to coordinate the callbacks so that you send the response after they all have completed. I suggest you use promises to accomplish this, fortunately Mongoose supports promises.

Promise.all([
    new_company.save(),
    new_branch.save(),
    new_user.save()
]).then(function (data) {
    res.send(data);
    console.log(data);
});

You are not handling the error correctly. Your if (err) statement will cause res.send(data) to be called when there is an error, this is certainly not desired. Using the promise based method defined above error handling is very simple.

Promise.all([
    new_company.save(),
    new_branch.save(),
    new_user.save()
]).then(function (data) {
    res.send(data);
    console.log(data);
}).catch(function (err) {
    res.status(400).send('Uh oh! Something bad happened.');
    console.error(err);
});

If you use ES6 syntax you can write a synchronous looking route, which may be more familiar if you are coming from a different language:

router.post('/create_company', async (req, res) => {
    try {
        const [company, branch, user] = req.body;
        const data = await Promise.all([
            new company.company(company).save(),
            new company.branch(branch).save(),
            new company.user(user).save()
        ]);
        res.send(data);
    } catch (err) {
        res.status(400).send('Uh oh! Something bad happened.');
        console.error(err);
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

thanks jake. very very usefull content. thanks again give your time for my code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.