node.js - 无法通过mongoose保存回调来访问变量

时间:2018-01-19 16:46:17

标签: node.js mongodb express mongoose callback

我正在尝试使用mongoose将数据保存到mongodb,然后发送json响应。 这是我的代码

var userdata = {
  name: req.body.name,
  username: req.body.username,
  email: req.body.email,
  password: req.body.password,
};

var resdata = {};

var user = new User(userdata);
user.save(function (error) {
  if(error) {
    if (error.name === 'MongoError' && error.code === 11000) {
      resdata =  { 
        status: false,
        errortype: 'db-error',
        message:  "Duplicate Key Error"
      };
    } else {

      resdata =  { 
        status: false,
        errortype: 'db-error',
        message:  error.message
      };
    }
  } else {

    resdata =  {
      status: true,
      message:  "User Registered Successfully.." 
    };
  }
});
res.send(resdata);

问题是我无法在save回调之外访问resdata的值。它总是返回{}。我该怎么办?

2 个答案:

答案 0 :(得分:2)

您必须在查询的回调中将数据发送到客户端,这是一个示例:

user.save(function (error) {
    if(error) {
        if (error.name === 'MongoError' && error.code === 11000) {

            res.json({
                status: false,
                errortype: 'db-error',
                message:  "Duplicate Key Error"
            });

        } else {

            res.json({
                status: false,
                errortype: 'db-error',
                message:  error.message
            });
        }
    } else {

        res.json({
            status: true,
            message:  "User Registered Successfully.." 
        });

    }
});

答案 1 :(得分:0)

this is my full code server.js

import express from 'express';
import morgan from 'morgan';
import mongoose from 'mongoose';
import router from './router';

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/myapp');

// Initialize http server
const app = express();

// Logger that outputs all requests into the console
app.use(morgan('combined'));
// Use v1 as prefix for all API endpoints
app.use('/', router);

// Launch the server on port 3000
const server = app.listen(3000, () => {
  const { address, port } = server.address();
  console.log(`Listening at http://${address}:${port}`);
});

router.js

import express, { Router } from 'express';
// Import register action from movies controller
import register  from './controllers/register';
import validator from 'express-validator';

// Initialize the router
const router = Router();

var bodyParser = require('body-parser');

router.use(bodyParser.json()); // support json encoded bodies
router.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
router.use(validator());

// Handle /movies.json route with register action from movies controller
router.post('/register', register.registerUser);

export default router;

register.js

  import mongoose from 'mongoose';
  import User from '../models/user';

  // Connect to MongoDB
  mongoose.connect('mongodb://localhost:27017/myapp', {useMongoClient: true});

  exports.registerUser = function(req, res) {

    req.checkBody('name', 'Name is required').notEmpty();
    req.checkBody('username', 'Username is required').notEmpty();
    req.checkBody('email', 'Email is required').notEmpty();
    req.checkBody('email', 'Email does not appear to be valid').isEmail();
    req.checkBody('password', 'Password is required').notEmpty();

    // check the validation object for errors
    var errors = req.validationErrors();

    console.log(errors);

    var resdata = {};

    if (errors) {

      resdata =  { 
        status: false,
        errortype: 'validation',
        message:  errors 
      };

      res.send(resdata);
    } else {

      var userdata = {
        name: req.body.name,
        username: req.body.username,
        email: req.body.email,
        password: req.body.password,
      };

      var user = new User(userdata);
      user.save(function (error) {

        var resdata = {};
        if(error) {
          if (error.name === 'MongoError' && error.code === 11000) {
            resdata =  { 
              status: false,
              errortype: 'mongoose-error',
              message:  "Duplicate Key Error"
            };
          } else {

            resdata =  { 
              status: false,
              errortype: 'mongoose-error',
              message:  error.message
            };
          }
        } else {

          resdata =  {
            status: true,
            message:  "User Registered Successfully.." 
          };
        }

        res.send(resdata);
      });
    }
  };