问题描述
当我使用nodejs操作mongodb时,读取数据和更新数据都是正常的,就是在插入数据时,报错了,提示:{ MongoError: Cannot read property ’maxBsonObjectSize’ of null
at Function.MongoError.create (C:UsersAdministratorAppDataRoamingnpmnode_modulesmongodbnode_modulesmongodb-coreliberror.js:31:11)at toError (C:UsersAdministratorAppDataRoamingnpmnode_modulesmongodblibutils.js:114:22)at C:UsersAdministratorAppDataRoamingnpmnode_modulesmongodblibcollection.js:656:23at handleCallback (C:UsersAdministratorAppDataRoamingnpmnode_modulesmongodblibutils.js:96:12)at resultHandler (C:UsersAdministratorAppDataRoamingnpmnode_modulesmongodblibbulkordered.js:429:14)at C:UsersAdministratorAppDataRoamingnpmnode_modulesmongodbnode_modulesmongodb-corelibwireprotocol2_4_support.js:473:9at _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] }有哪位朋友遇到过这个问题吗?
问题解答
回答1:这里的maxBsonObjectSize是不是数据库文档里的一个字段?如果是的话,就算你不想在maxBsonObjectSize插入值,在插入数据时也要给它一个空值,例如空字符串’’,空数组[]等。
回答2:看看是不是在插入回调之前把关闭数据库链接关闭了。
MongoClient.connect(uri, function (err, db) { if (err) {throw err; } else {console.log('successfully connected to the database');// Insert document in MongoDb Collectionvar 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();应该放在插入的回调里。像这样:
MongoClient.connect(uri, function (err, db) { if (err) {throw err; } else {console.log('successfully connected to the database');// Insert document in MongoDb Collectionvar 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();}); }});