1

I have a MongoDB connected to Node.js Express, and I have an API controller that accepts POST request and .save() the request body to the database. Yet, even if it console logged the request body correctly and entered inside the .save() method, I checked the terminal with mongo->db, but still nothing got created.

Is there a way to determine if MongoDB is actually using the MongoDB .save() method? And also how can I check if the MongoDB is properly connected to the server?

Tried express logging as well:

enter image description here

And here is how the server is set up:

const express = require('express'),
      app = express(),
      logger = require('morgan'),
      config = require('./config/main'),
      mongoose = require('mongoose'),
      bodyParser = require('body-parser'),
      router = require('./router');

mongoose.Promise = global.Promise;
mongoose.connect(config.database);

const server = app.listen(config.port);
console.log('Your server is running on port ' + config.port + '.');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logger('dev'));

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost:8080");
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Allow-Credentials");
  res.header("Access-Control-Allow-Credentials", "true");
  next();
})

router(app);

And the configuration for the server:

module.exports = {
  'database': 'mongodb://localhost/testdatabase',
  'port': process.env.PORT || 3000,
  'secret': 'secretsecret',
}

EDIT 2

My .save in controller:

  user.save(function(err, user) {
      if(err) { return next(err); }

      res.status(201).json({
        user: user
      })
    }) 

EDIT 3 Tried logging with mongoose.set('debug', true); and got the following:

enter image description here

Jo Ko
  • 7,225
  • 15
  • 62
  • 120
  • here are some answers : http://stackoverflow.com/questions/6854431/how-do-i-get-the-objectid-after-i-save-an-object-in-mongoose – Milos Lulic Sep 09 '16 at 07:40
  • @MilosLulic sorry but can't seem to discern what's what I'm looking for. Can you help – Jo Ko Sep 09 '16 at 08:50
  • If using `mongoose`, simply check if `save()` completes or not : `mydoc.save().then(function(d){console.log('SAVED',d);})` – S.D. Sep 09 '16 at 09:48
  • @S.D. I updated the original post with the .save. Where should the `mydoc.save().then(function(d){console.log('SAVED',d);})` go? – Jo Ko Sep 09 '16 at 17:22
  • @JoKo what IDE are you using ? If you are using something like [vscode](https://code.visualstudio.com/), then you can simply place a break point in callback function and debug the code. – S.D. Sep 13 '16 at 04:23

1 Answers1

1

You can set mongoose to debug mode to see whats going on.

mongoose.set('debug', true);
Johannes Merz
  • 3,252
  • 17
  • 33