Node.js Mongoose模型没有保存而没有错误

时间:2017-01-23 13:29:12

标签: node.js mongodb express mongoose

制作这个简单的Node.js Express API我遇到了一个奇怪的问题: 我正在创建一个模型并将数据插入其中,然后将其保存到我的MongoDB中。但记录从未保存过,但我也没有收到任何错误。我已经检查了MongoDB是否正在运行以及是否存在针对Node错误的syslog以及用于MongoDB错误的mongod.log以及我自己的Wilson debug.log文件。全部都没有错误。

我使用postman来测试API并且每次都会得到响应。只是数据没有保存到MongoDB(我使用mongo控制台和db.collection.find()来检查插入的记录)。

知道为什么会这样吗?

我的代码:

api.js

var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');
var http       = require('http');
var https      = require('https');
var fs         = require('fs');
var winston    = require('winston');

// Configure logging using Winston
winston.add(winston.transports.File, { filename: '/home/app/api/debug.log' });
winston.level = 'debug';

// Request body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// Enable https 
var privateKey  = fs.readFileSync('path to private key');
var certificate = fs.readFileSync('path to cert file');

var credentials = {
    key: privateKey,
    cert: certificate
};

// ROUTERS
var router = express.Router();

var speciesRouter = require('./app/routes/speciesRouter');
router.use('/species', speciesRouter);

// Routes prefix
app.use('/api/v1', router);

// SERVER STARTUP
http.createServer(app).listen(3000);
https.createServer(credentials, app).listen(3001);

speciesRouter.js

var express  = require('express');
var mongoose = require('mongoose');
var router   = express.Router();
var Sighting = require('../models/sighting');
var winston  = require('winston');

// Database connection
var dbName = 'dbname';
mongoose.connect('mongodb://localhost:27017/' + dbName);
var db = mongoose.connection;
db.on('error', function(err){
  winston.log('debug', err);
});

router.route('/')

.post(function(req, res) {

  var sighting = new Sighting();
  sighting.user_key = req.body.user_key;
  sighting.expertise = req.body.expertise;
  sighting.phone_location = req.body.phone_location;
  sighting.record_time = req.body.record_time;
  sighting.audio_file_location = '/var/data/tjirp1244123.wav';
  sighting.probable_species = [{species_name:'Bosaap', percentage:100}];

  var error = '';
  winston.log('debug', 'test');

  // This does not get execute I suspect..
  sighting.save(function(err) {
    winston.log('debug', 'save');
    if (err) {
      winston.log('debug', err);
      error = err;
    }
  });

  res.json({ 
    probable_species: probable_species,
    expertise: req.body.expertise,
    error: error
  });
});

module.exports = router;

sighting.js(模特)

var mongoose = require('mongoose');
var Schema   = mongoose.Schema;

var SightingSchema = new Schema({
  user_key: String,
  expertise: Number,
  phone_location: { lat: Number, lng: Number },
  record_time: Number,
  audio_file_location: String,
  probable_species: [{ species_name: String, percentage: Number }]
});

module.exports = mongoose.model('Sighting', SightingSchema);

2 个答案:

答案 0 :(得分:1)

您是否尝试过更新mongodb。

sudo npm update

答案 1 :(得分:0)

你可以尝试使用诺言。

return sighting.save().then(function(data){
   console.log(data); // check if this executes
   return res.json({ 
      probable_species: probable_species,
    expertise: req.body.expertise,
    error: error
    });
}).catch(function(err){
   console.log(err);
});

在保存函数之外不要使用res.json,因为在异步代码中它将运行而不等待保存函数来完成其执行