Michael
Michael

Reputation: 11904

MongoDB. Undefined record inserted. Cannot read property 'title' of undefined

Im newbie in MongoDB. Once started immediately got the error. I have a simple code

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

and here is the error message

enter image description here

Help me please to understand what this error and how to fix it. If you do not complicate.

MongoDB version 3.0.7

Upvotes: 0

Views: 1947

Answers (3)

Đức Anh Nguyễn
Đức Anh Nguyễn

Reputation: 21

you should replace the former code with this

console.log(docs.ops.length + ' record inserted.');
console.log(docs.ops[0].title + ' – ' + docs.ops[0]._id);

Upvotes: 2

shell_bug
shell_bug

Reputation: 21

Create connection and insert to MongoDB

I use MongoDB 3.2.0 and mongodb node.js driver 2.1.14

Install Node.js MongoDB driver and BSON with npm

npm install mongodb bson

and INSERT operation looks like this

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

Upvotes: 1

jiwoong
jiwoong

Reputation: 1

I used module mongodb 2.0.49 and database mongodb3.0

After Inserting to testing collection, docs is not the documents of testing collection.

docs is result of query.

It will looks like

{ result: { ok: 1, n: 1 },
  ops: [ { 'it's you query'} ],
  insertedCount: 1,
  insertedIds: [ 'blah blah blah' ] }

So, docs is not Array but json.

That's why docs[0] is undefined("docs is not array!!!!")

Upvotes: 0

Related Questions