I'm trying to get some data to save into MongoDb. I followed the following example beforehand and verified that it works, however now that I'm trying to write my own test app using this "format" it's not working. MongoDb does not throw any errors and I can even retrieve the doc _id from the insert callback. However when I go into the Mongo shell, the collection doesn't even exist let alone the document.
Here's the example I followed originally just so you can get a feel for the way I tried to mimic for my own test app:
http://blog.ijasoneverett.com/2013/03/a-sample-app-with-node-js-express-and-mongodb-part-1/
Below is my attempt that is failing. Thanks for any help!
Here's my DB code:
var Db = require('mongodb').Db,
Connection = require('mongodb').Connection,
Server = require('mongodb').Server,
BSON = require('mongodb').BSON,
ObjectID = require('mongodb').ObjectID;
Repository = function(host, port){
this.db = new Db('test-mongo-db', new Server(host, port, {safe: true}, {auto_reconnect:true}, {}));
this.db.open(function(){
console.log('db open');
});
};
Repository.prototype.getCollection = function(callback){
this.db.collection('owners', function(error, owners_collection){
if (error) callback(error);
else
callback(null, owners_collection);
});
};
Repository.prototype.createOwner = function(owner, callback){
this.getCollection(function(error, owners_collection){
if (error) callback(error);
else {
owners_collection.insert(owner, function(error, doc){
if (error) callback(error);
else {
console.log('insert was successful: ' + doc[0]['_id']);
callback(null, owner);
}
});
}
});
};
exports.Repository = Repository;
Here's the code that's calling it:
var Repository = require('../repositories/Repository').Repository;
exports.createOwner = function(req, res){
var owner = {
email : req.body.email,
password : req.body.password,
firstName : req.body.firstName,
lastName : req.body.lastName,
schools : []
};
var repository = new Repository('localhost', 27017);
repository.createOwner(owner, function(error, docs){
if (error) console.log('saving owner failed : ' + error);
else {
console.log('saving owner successful');
res.redirect('/');
}
});
};
If @cristkv is right, you can try to add optional parameter write concern in the insert operation:
owners_collection.insert(owner, {w:1}, function(error, doc){
sources:
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insert