0
votes

Making this simple Node.js Express API I encountered an odd problem: I am creating a model and inserting data into it and then saving it to my MongoDB. But the record is never saved but I also don't get any error. I have checked if MongoDB is running and both syslog for Node errors and mongod.log for MongoDB errors as well as my own Wilson debug.log file. All contain no errors.

I use postman to test the API and do get a response every time. It's just that the data does not get saved to MongoDB (I used the mongo console with db.collection.find() to check for inserted records).

Any idea why this could be happening?

my code:

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 (model)

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
winston.log('debug', 'save'); this prints something? - Asif Saeed
this puts it in my custom log file, yes. That line never gets reached, however putting another winston log before the sighting.save() line does get reached. - NG.
I checked db.calculations.find() as well as db.sightings.count(). the first was empty, the second returned 0. - NG.
Your code is saving to the dbname database, is that where you're looking? - JohnnyHK
Yes, i checked :) - NG.

2 Answers

1
votes

Did you try updating your mongodb.

sudo npm update
0
votes

You can try using promise.

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

One more thing dont use res.json outside the save function because in async code it will run without waiting for save function to complete its execution