简体   繁体   中英

Mongoose .save() not saving to database?

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} {'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:

在此处输入图片说明

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

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM