猫鼬.save()是否不保存到数据库? [英] Mongoose .save() not saving to database?

查看:107
本文介绍了猫鼬.save()是否不保存到数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的猫鼬.save方法有问题.永远不会创建数据库,也不会保存数据,也不会引发任何错误.我已经用尽了google和stackoverflow在没有运气的情况下寻找类似的建议,所以将其开放给任何可以帮助我的人!

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!

我的POST请求是通过以下方式发出的:

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

我发出了多个POST请求,并且都通过服务器配置{'database': 'mongodb://localhost/practicedb', 'port': process.env.PORT || 3000}从API返回了成功状态,但是数据从未保存过,并且数据库(practicedb)也未显示在终端上.

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.

具有猫鼬模式(user.js):

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

API控制器

接收电子邮件字符串POST请求,然后如果在文本字段中未输入任何内容,则发送回422错误,而在User.findOne内部,如果数据库中已经存在该电子邮件,则抛出422错误如果不是,则执行user.save将其保存在数据库中.但是.save不能正常工作,甚至无法创建数据库.

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,
      })
    })
  })
}

编辑

我尝试了API控制器的更广泛的控制台日志记录,一旦被触发,看起来它什么也没执行,并跳到了结尾,但是随后它又重新拾起并放入User.findOne和user.save中,但是看起来user.save无法正常工作.

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.

是服务器未正确连接到数据库吗?是否可以确定是否正在使用MongoDB方法?

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

编辑2

推荐答案

我实际上花了最后4个小时来弄清楚为什么.save()无法正常工作.原来我的家庭IP地址已更改,无法访问数据库. ARGH

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:

执行console.log(mongoose.connection.readyState)

该代码将返回数据库状态.如果返回1,则表明您已连接.如果返回0,则表示您未连接. 请参阅此答案以获取完整列表

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

如果返回0,则可以尝试将IP地址列入白名单(假设您使用的是MongoDB Atlas):

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

  1. 转到您的MongoDB Atlas仪表板.
  2. 转到安全性"下的Network Access
  3. Add IP Address
  4. 添加您当前的IP地址
  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

这篇关于猫鼬.save()是否不保存到数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆