I am currently unsuccessfully trying to persist document to mongodb using nodejs and mongoosejs.
This my code structure:
The start.js simply initializes my app and creates mongod connection detailed in mongodb.js. The connection is succesfully established and can be seen in mongodb console.
this my model.js
var mongoose = require('mongoose');
var regSceham = new mongoose.Schema({
userId: String,
name:String,
mob:String,
email:String
})
var RegistrationModel = mongoose.model('registration', regSceham);
exports.RegistrationModel = RegistrationModel;
this is my datalayer.js:
var mongoose = require('mongoose');
var mongodb = require('./mongodb');
var model = require('./model');
//var RegistrationModel = mongoose.model('RegistrationModel');
/////////////////////////////////
function save(data){
console.log('inside save >>>>> ' + data);
var regModel = new model.RegistrationModel(data);
console.log('after model');
regModel.save(function(err,regModel){
console.log('inside mongoose save');
if(err)
console.log(err);
});
}
require('./model')
exports.save = save;
when I call the save method in datalayer.js the "inside save >>>>> " statement logged to console and then nothing happens. It seems the var regModel = new model.RegistrationModel(data);
statement fails without any error and I donot have any clue why. Any suggestion would be highly appreciated.
sample post data as requested :
{
"userId":"tesrwetId",
"name":"Test",
"mob":"2536245632",
"email":"ashdjas@sa.com"
}
Update 24/06
I am starting to think that since the connection to mongoose is established after my model initialization this problem is experienced. I am unable to get the connection to happen before model is initialized.
Below is the file initialisation sequence. Though the mongodb.js(the mongoose connection) is initilaized first, the on connect method gets called after model.js is initialized.
The mongodb.js file:
console.log('mongodb....');
var mongoose = require('mongoose');
var configure = require('./configure');
// create database
//console.log('sadasdasdsa >>>>>>>' + configure.creds.mongodb)
mongoose.connect(configure.creds.mongodb);
mongoose.connection.on('connected', function () {
console.log('MOngodb connection open to ' + configure.creds.mongodb);
require('./model');
});
// If the connection throws an error
mongoose.connection.on('error',function (err) {
console.log('MOngodb connection error: ' + err);
});
// When the connection is disconnected
mongoose.connection.on('disconnected', function () {
console.log('MOngodb connection disconnected');
});
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('MOngodb connection disconnected through app termination');
process.exit(0);
});
});
require('./model');
update 28/06
I have since realised this understanding regarding loading sequence is incorrect. read here