【问题标题】:Mongoose .save() not saving to database?Mongoose .save() 不保存到数据库?
【发布时间】:2017-01-16 22:52:32
【问题描述】:

我遇到了 Mongoose .save 方法的问题。永远不会创建数据库,也不会保存数据,也不会引发任何错误。我已经用尽了谷歌和 stackoverflow 来寻找类似的建议,但没有运气,所以把它开放给任何可以帮助我的人!

我的 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 请求,所有请求都从 API 返回成功状态,服务器配置为:{'database': 'mongodb://localhost/practicedb', 'port': process.env.PORT || 3000},但数据从未保存,数据库 (practicedb) 未显示在终端上。

使用 Mongoose 架构 (user.js):

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

API 控制器

接收到邮件字符串POST请求,然后如果在文本字段中没有输入,则返回422错误,在User.findOne内,如果数据库中已经存在邮件,则抛出422错误如果没有,user.save 是否将其保存在数据库中。但是 .save 不能正常工作,甚至没有创建数据库。

"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 不起作用。

会不会是服务器没有正确连接到数据库?有没有办法确定是否使用了 MongoDB 方法?

也尝试过快速日志记录:

这是服务器的设置方式:

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

【问题讨论】:

  • 你的 user.js 是完整的吗?当你声明一个猫鼬模式并返回一个模型?
  • @LucasCosta 抱歉,您能澄清一下什么是完整的吗?
  • @LucasCosta 抱歉,你指的是“他们”是谁?
  • user.save(function(err, user) { 之后可以做console.log 看看回调中发送了什么,例如:console.log(err, user);
  • @RandomUser 按照建议尝试了 console.log(err,user) 并记录了 null { __v: 0, email: 'testemail@test.com', _id: 57d2eea0d739b312704d0491 } 任何线索?

标签: node.js mongodb express reactjs mongoose


【解决方案1】:

我确实花了最后 4 个小时试图弄清楚为什么 .save() 不起作用。原来我的家庭 IP 地址已更改,无法访问数据库。啊

无论如何...这是我诊断问题的方法:

console.log(mongoose.connection.readyState)

该代码将返回数据库状态。如果它返回1,则表示您已连接。如果它返回0,则表示您未连接。 See this answer for the full list

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

  1. 转到您的 MongoDB Atlas 仪表板。
  2. 转到安全下的Network Access
  3. 点击Add IP Address
  4. 添加您当前的 IP 地址

【讨论】:

    【解决方案2】:

    我遇到了类似的问题,因为我没有查看数据库中的正确位置,所以这些项目没有显示出来。您确定您已连接到 mongodb 数据库。 Mongoose 有时会进行操作缓冲。试试这个以确保您已连接:

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

    更多关于操作缓冲的细节:http://mongoosejs.com/docs/connections.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      • 1970-01-01
      • 2021-05-29
      • 1970-01-01
      • 2014-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多