[英]MongoDB. Undefined record inserted. Cannot read property 'title' of undefined
我是MongoDB中的新手。 一旦開始,立即出現錯誤。 我有一個簡單的代碼
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/mongotest',
function(err, db) {
console.log('Connected to MongoDB!');
// using the db connection object, save the collection 'testing' to
// a separate variable:
var collection = db.collection('testing');
// isert a new item using the collection's insert function:
collection.insert({
'title': 'Snowcrash'
}, function(err, docs) {
// on successful insertion, log to the screen the new
// collection's details:
console.log(docs.length + ' record inserted.');
console.log(docs[0].title + ' – ' + docs[0]._id);
// finally close the connection:
db.close();
});
});
這是錯誤消息
請幫助我了解此錯誤以及如何解決。 如果您不復雜。
MongoDB版本3.0.7
你應該用這個替換以前的代碼
console.log(docs.ops.length + ' record inserted.');
console.log(docs.ops[0].title + ' – ' + docs.ops[0]._id);
創建連接並插入到MongoDB
我使用MongoDB 3.2.0和mongodb node.js驅動程序2.1.14
使用npm安裝Node.js MongoDB驅動程序和BSON
npm install mongodb bson
和INSERT操作看起來像這樣
var mongodb = require('mongodb');
var bson = require('bson');
// Create Connection
var server = new mongodb.Server('127.0.0.1', '27017', {});
var client = new mongodb.Db('mydb', server, {w:1});
client.open(function(error){
if(error)
throw error;
// Create MongoDB Collection
client.collection('mongodb_insert', function(error, collection) {
if(error)
throw error;
console.log('Connection!')
// CREATE/INSERT Operation
collection.insert(
{
"key": "value",
"key1": "value1"
},
{safe: true},
function(error, document)
{
if(error)
throw error;
console.log(document);
}
)
})
})
我使用了模塊mongodb 2.0.49
和database mongodb3.0
插入測試集合后,docs不是測試集合的文檔。
docs是查詢的結果。
看起來像
{ result: { ok: 1, n: 1 },
ops: [ { 'it's you query'} ],
insertedCount: 1,
insertedIds: [ 'blah blah blah' ] }
因此,docs不是Array,而是json。
這就是為什么docs [0]未定義的原因(“ docs不是數組!!!”)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.