1

我正在尝试获取一些数据以保存到 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('/');
        }

    });
};
4

1 回答 1

0

如果@cristkv 是正确的,您可以尝试在插入操作中添加可选参数写入关注:

owners_collection.insert(owner, {w:1}, function(error, doc){

来源:

http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insert

http://docs.mongodb.org/manual/core/write-concern/

于 2015-04-20T05:53:18.960 回答