2

I am having problem with Mongoose .save method. The database never gets created and data do not get saved, and does not throw any errors. I've exhausted google and stackoverflow looking at similar suggestions with no luck, so throwing it open to anyone who can help me!

My POST request is made with:

export function registerUser({ email }) {
  return function(dispatch) {
    axios.post(`${API_URL}/auth/register`, { email })
    .then(response => {
      dispatch({ type: AUTH_USER });
    })
    .catch((error) => {
      errorHandler(dispatch, error.response, AUTH_ERROR)
    });
  }
}

I made several POST requests and all get successful status back from API with sever config: {'database': 'mongodb://localhost/practicedb', 'port': process.env.PORT || 3000}, yet the data never gets saved and database (practicedb) doesn't show up on Terminal.

With a Mongoose Schema (user.js):

var UserSchema = new Schema({
  email: {
    type: String,
    lowercase: true,
    unique: true,
    required: true
  },
})

API controller

That receives the email string POST request, and then if nothing is entered in the text field, it sends back a 422 error, and inside User.findOne, if the email already exists in the database, then it throws a 422 error and if not, does user.save to save it in the database. But .save does not work with no errors and the database doesn't even get created.

"use strict";

const User = require('../models/user')

exports.register = function(req, res, next) {
  const email = req.body.email;

  if(!email) {
    return res.status(422).send({ error: 'You must enter an email address.'})
  }

  User.findOne({ email: email }, function(err, existingUser) {
    if(err) { return next(err); }

    if(existingUser) {
      return res.status(422).send({ error: 'That email address is already in use.'})
    }
    let user = new User({
      email: email,
    })
    user.save(function(err, user) {
      if(err) { return next(err); }
      res.status(201).json({
        user: user,
      })
    })
  })
}

EDIT

I tried more extensive console logging for the API controller and once triggered, looks like it doesn't execute anything and skips to the ends, but then it picks back up and goes inside both User.findOne and user.save, yet looks like user.save is not working.

Could it be that the server is not properly connected to the database? Is it there a way to determine if MongoDB methods are being used?

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);

EDIT 2

enter image description here

  • Your user.js is complete? When you declare a mongoose schema and returns a model? – BrTkCa Sep 08 '16 at 21:47
  • @LucasCosta Sorry but could you clarify on what is complete? –  Sep 08 '16 at 22:55
  • @LucasCosta Sorry but who are you referring to as 'they'? –  Sep 09 '16 at 00:16
  • After `user.save(function(err, user) {` can you do console.log to see what was sent in the callback, ex: `console.log(err, user);` – Dhruv Kumar Jha Sep 09 '16 at 08:31
  • @RandomUser Tried console.log(err,user) as suggested and it logged `null { __v: 0, email: 'testemail@test.com', _id: 57d2eea0d739b312704d0491 }` Any clue? –  Sep 09 '16 at 17:19
  • That means its successfully being saved in database, do check your database again.. maybe you're missing something. – Dhruv Kumar Jha Sep 09 '16 at 17:24
  • @RandomUser That's what I am thinking and just did but still database `practicedb`... Updated the original post with a screenshot. The command should be `mongo` then `db` correct? I am only seeing `test` db, which I never even created. –  Sep 09 '16 at 17:37
  • First, check the MongoDB connection details in your app and then check the corresponding database + collection., It would be better if we chat somewhere instead of communicating like this... – Dhruv Kumar Jha Sep 09 '16 at 17:39
  • @RandomUser Definitely. Are you not able to open chat with me? Or we can use http://collabedit.com/tr3j4 I am inside it –  Sep 09 '16 at 17:52
  • @JohnBana I didn't knew we could chat using Stackoverflow... – Dhruv Kumar Jha Sep 09 '16 at 18:11
  • What is your collection name? Where/how are you creating model? – Mohammed Amir Ansari Oct 07 '19 at 05:24

2 Answers2

6

I literally spent the last 4 hours trying to figure out why .save() would not work. Turns out my home IP address changed and could not access the database. ARGH

Anyways... here's how I diagnosed my problem:

Do console.log(mongoose.connection.readyState)

That code will return the database state. If it returns 1 that means you're connected. If it returns 0 that means you're not connected. See this answer for the full list

If it returns 0 you can try whitelisting your IP address (assuming you're using MongoDB Atlas):

  1. Go to your MongoDB Atlas Dashboard.
  2. Go to Network Access under Security
  3. Hit Add IP Address
  4. Add your current IP Address
radihuq
  • 999
  • 10
  • 13
0

I had a similar issue and the items were not showing up because I was not looking at the correct location in the database. Are you sure you have connected to the mongodb database. Mongoose does operation buffering at times. try this to make sure you are connected :

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!
});

// from mongoose docs. 

More details about operation buffering : http://mongoosejs.com/docs/connections.html

nnrales
  • 1,481
  • 1
  • 17
  • 26