Or05230
Or05230

Reputation: 83

Can't save to mongoDB's database

While sending a post request i written the following code :

 var email = req.body.email ; 
 var newDetails = { email: email };
  Details.create(newDetails);
 console.log(newDetails);

while sending the request. The console.log shows me the correct details, However in the mongo shell the only collection that exist is "details" and it's empty . That's the Mongoose Schema:

var mongoose = require("mongoose");

var DetailsSchema = mongoose.Schema({
    email: String
});

module.exports = mongoose.model("Details", DetailsSchema);

I'm using NodeJS. Thanks in advance.

Upvotes: 0

Views: 1658

Answers (2)

Sunny
Sunny

Reputation: 1456

To save data in mongoDB's Database You can use this way

var detailsData = new detailsModel();
  detailsData.save()
    .then(business => {
      res.status(200).json({'Details': 'newDetails added successfully'});
    })
    .catch(err => {
    res.status(400).send("unable to save to database");
    });

With this, you can also handle error easily.

Upvotes: 0

Parth Raval
Parth Raval

Reputation: 4423

Your Mongoose Model should be like

const mongoose = require("mongoose");
const Scheme = mongoose.Schema;

const DetailsSchema = new Scheme({
    email: String
});

module.exports = mongoose.model("Details", DetailsSchema);

Node js Code should be like

var detailsModel = require('../model/Details.js');//path of mongoose model


var detailsData = new detailsModel();
        detailsData.email = req.body.email; 
        detailsData.save(function (err, savedJob) {
      if (err) {
        return res.send(err);
      } else {
         return res.send(savedJob);
      }
});

Upvotes: 1

Related Questions