node.js - 使用nodejs往mongodb中插入数据时出错
高洛峰
高洛峰 2017-04-17 14:50:47
0
2
563

当我使用nodejs操作mongodb时,读取数据和更新数据都是正常的,就是在插入数据时,报错了,提示:
{ MongoError: Cannot read property 'maxBsonObjectSize' of null

at Function.MongoError.create (C:\Users\Administrator\AppData\Roaming\npm\node_modules\mongodb\node_modules\mongodb-core\lib\error.js:31:11)
at toError (C:\Users\Administrator\AppData\Roaming\npm\node_modules\mongodb\lib\utils.js:114:22)
at C:\Users\Administrator\AppData\Roaming\npm\node_modules\mongodb\lib\collection.js:656:23
at handleCallback (C:\Users\Administrator\AppData\Roaming\npm\node_modules\mongodb\lib\utils.js:96:12)
at resultHandler (C:\Users\Administrator\AppData\Roaming\npm\node_modules\mongodb\lib\bulk\ordered.js:429:14)
at C:\Users\Administrator\AppData\Roaming\npm\node_modules\mongodb\node_modules\mongodb-core\lib\wireprotocol\2_4_support.js:473:9
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)

name: 'MongoError',
message: 'Cannot read property 'maxBsonObjectSize' of null',
driver: true,
code: 14,
index: 0,
errmsg: 'Cannot read property 'maxBsonObjectSize' of null',
getOperation: [Function],
toJSON: [Function],
toString: [Function] }
有哪位朋友遇到过这个问题吗?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
Ty80

Is the maxBsonObjectSize here a field in the database document? If so, even if you don't want to insert a value in maxBsonObjectSize, you should give it a null value when inserting data, such as empty string '', empty array [], etc.

大家讲道理

See if the close database link is closed before inserting the callback.

MongoClient.connect(uri, function (err, db) {
    if (err) {
        throw err;
    } else {
        console.log("successfully connected to the database");

        // Insert document in MongoDb Collection
                var document = {title:'test',category:'node.js'}

                db.collection('tut').insert(document, function(err,records){
                        //if (err) throw err;
                        console.log('inserted record id: ' + records[0]._id);
                  });
    }
    // @Warning: 这里会出错!
    db.close();
});

db.close(); should be placed in the inserted callback. Like this:

MongoClient.connect(uri, function (err, db) {
    if (err) {
        throw err;
    } else {
        console.log("successfully connected to the database");

        // Insert document in MongoDb Collection
        var document = {title:'test',category:'node.js'}

        db.collection('tut').insert(document, function(err,records){
            //if (err) throw err;
            console.log('inserted record id: ' + records[0]._id);
            // ###像这样,放在会调里关闭连接
            db.close();
        });
    }
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template