我正在尝试将一些数据保存到MongoDb中。我事先按照以下示例验证它是否有效,但是现在我正在尝试使用这种“格式”编写自己的测试应用程序,但它无法正常工作。 MongoDb不会抛出任何错误,我甚至可以从插入回调中检索doc _id。但是,当我进入Mongo shell时,该集合甚至不存在,更不用说文档了。
以下是我最初遵循的示例,以便您可以了解我尝试模仿自己的测试应用的方式:
http://blog.ijasoneverett.com/2013/03/a-sample-app-with-node-js-express-and-mongodb-part-1/
以下是我失败的尝试。谢谢你的帮助!
这是我的数据库代码:
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;
以下是调用它的代码:
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('/');
}
});
};
答案 0 :(得分:0)
如果@cristkv是正确的,您可以尝试在插入操作中添加可选参数写入问题:
owners_collection.insert(owner, {w:1}, function(error, doc){
来源:
http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insert