获取错误node.js mongodb成功插入后无法读取记录的null属性0

编程入门 行业动态 更新时间:2024-10-28 20:26:11
本文介绍了获取错误node.js mongodb成功插入后无法读取记录的null属性0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用db.collection.insert方法在mongodb中使用function(err,records)回调添加了一个文档.尽管插入成功(我在mongolab上检查了记录),但记录为null,因此在记录[0]上出现错误._id

I used db.collection.insert method to add a document in mongodb with function(err,records) callback. Though insertion succeeds (I checked on mongolab the record), records is null so that It throws error at records[0]._id

我正在测试的是nitroous.io上的node.js错误吗?

Is it a node.js bug on nitrous.io which I'm testing ?

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(); });

推荐答案

您要在insert调用完成之前关闭连接.将您的db.close();调用移至回调内:

You're closing the connection before the insert call completes. Move your db.close(); call inside 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); db.close(); }); } });

请记住,您不应该经常打开和关闭MongoClient连接池.通常最好在启动过程中将其打开,并保持打开状态,直到您的应用关闭.

Keep in mind that you shouldn't be frequently opening and closing your MongoClient connection pool. It's generally best to open it during startup and leave it open until your app shuts down.

更多推荐

获取错误node.js mongodb成功插入后无法读取记录的null属性0

本文发布于:2023-11-28 09:17:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641815.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   错误   node   js   mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!