shireef khatab
shireef khatab

Reputation: 1005

Mongoose doesn't save documents to my database locally

My problem is simple as i guess. i can run mongoose to save documents to my DB on mlab. also can see the saved data via postman on get requests. but when i use local mongodb instead of mlab then try to show the db collections on my terminal by running "mongo" then select the same db to which mongoose is connected it shows me an empty db. i try again to send post request with new data.. and the result is same, positive on postman and mlab, but when connect to local mongodb and post new data.. there is nothing there at all. the only way i can insert data to my shell is through the command insert().

Any idea why is this happening? Thank you in advance.

app.js

        var express = require("express");
        var app = express();
        var port = 8080;
        var bodyParser = require('body-parser');
        app.use(bodyParser.json());
        app.use(bodyParser.urlencoded({ extended: true }));

        var mongoose = require("mongoose");
        mongoose.Promise = global.Promise;
        mongoose.connect("mongodb://localhost:27017/test",{ useNewUrlParser: true });


        // Model & Schema
        var nameSchema = new mongoose.Schema({
            firstName: String,
            lastName: String
        });
        var User = mongoose.model("User", nameSchema);



        // Routes
        app.get('/users', (req, res) => {
            User.find({}, (err, user) => {
                if (err) throw err;
                console.log(user)
                res.send(user)
            })
        })
        app.post("/addname", (req, res) => {
            var myData = new User(req.body);
            myData.save()
            .then(item => {
            res.send("item saved to database");
            })
            .catch(err => {
            res.status(400).send("unable to save to database");
            });
        });



        app.use("/", (req, res) => {
            res.sendFile(__dirname + "/index.html");
        });

        app.listen(port, () => {
        console.log("Server listening on port " + port);
        });

Here when i use mlab:

enter image description here

enter image description here

enter image description here

BUT when using local machine..:

enter image description here

enter image description here

enter image description here

Upvotes: 2

Views: 1961

Answers (1)

Ratan Uday Kumar
Ratan Uday Kumar

Reputation: 6512

try like below in add api

app.post("/addname", (req, res) => {
    req.body = JSON.parse(JSON.stringify(req.body)); //This line is Optional, some time req.body is in json buffer form so we are converting to pure json
    User(req.body).save().then(item => {
        console.log("DB Item saved --->", item);
        res.status(200).send("item saved to database");
    }).catch(err => {
        res.status(400).send("unable to save to database");
    });
});

dont forget that req.body must contain firstName, lastName

After your Question update regarding the listing of Collection(Schema) Documents

Your are trying

db.test.find()

which will not work because Your Schema name is User and will save as users since mongodb prefer Plural collection names because it consists of more than One Documents

You must try

db.users.find() in your mongo shell

It will return all documents of User Collections.

If you want specific collection name(Schema name) then you have to create schema as below

// Model & Schema
var nameSchema = new mongoose.Schema({
    firstName: String,
    lastName: String
}, { collection: 'User' });
var User = mongoose.model("User", nameSchema);

In mongo shell you must try like

db.User.find();

For listing all collection in mongo shell you must try like below

db.getCollectionNames()

Upvotes: 3

Related Questions