[Help needed] learnyoumongo - Exercise 5: Insert

Hi,

I’m currently working on exercise 5 of learnyoumongo, but I’m stuck…
This is my solution:

var MongoClient = require("mongodb").MongoClient;

var url = "mongodb://localhost:27017/learnyoumongo";
var firstName = process.argv[2];
var lastName = process.argv[3];

MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    
    var docs = db.collection('docs');
    
    docs.insert({
        'firstName': firstName,
        'lastName': lastName
    }, function(err, data) {
        if (err) throw err;
        
        console.log(JSON.stringify(data));
        db.close();
    });
});

It fails when I run learnyoumongo verify program.js:

{ [AssertionError: { insertedCount: 1,
insertedIds: [ ‘5805ecde7098de06a825162e’ ],
ops:
[ { firstName: ‘John’,
lastName: ‘George’,
deepEqual { firstName: ‘John’, lastName: ‘George’ }]
name: ‘AssertionError’,
actual:
{ insertedCount: 1,
insertedIds: [ ‘5805ecde7098de06a825162e’ ],
ops: [ [Object] ],
result: { ok: 1, n: 1 } },
expected: { firstName: ‘John’, lastName: ‘George’ },
operator: ‘deepEqual’,
message: ‘{ insertedCount: 1,\n insertedIds: [ '5805ecde7098de06a825162e' ],\n ops: \n [ { firstName: 'John',\n lastName: 'George',\n deepEqual { firstName: 'John', lastName: 'George' }’,
generatedMessage: true }
✗ { insertedCount: 1,
insertedIds: [ ‘5805ecde7098de06a825162e’ ],
ops:
[ { firstName: ‘John’,
lastName: ‘George’,
deepEqual { firstName: ‘John’, lastName: ‘George’ }

FAIL

Your solution to INSERT didn’t pass. Try again!

But if I run it with node program.js I get:
{"result":{"ok":1,"n":1},"ops":[{"_id":"5805ed9d11eaf606c6b10be5"}],"insertedCount":1,"insertedIds":["5805ed9d11eaf606c6b10be5"]}.

I don’t understand what’s wrong with my solution…

Thanks in advance for the help!

I looked at your code and couldn’t see any obvious errors so I just went to the learnyoumongo GitHub page and looked at the solution - they want you to stringify not the result of the insertion, but the data you are inserting.

Use console.log to print out the object used to create the document.

Make sure you use JSON.stringify convert it to JSON.

So it should be:

...
console.log(JSON.stringify({
        'firstName': firstName,
        'lastName': lastName
    }));
...
2 Likes

You’re right, this worked:

var MongoClient = require("mongodb").MongoClient;

var url = "mongodb://localhost:27017/learnyoumongo";
var firstName = process.argv[2];
var lastName = process.argv[3];

MongoClient.connect(url, function(err, db) {
    if (err) throw err;

    var docs = db.collection('docs');

    var doc = {
        'firstName': firstName,
        'lastName': lastName
    };

    docs.insert(doc, function(err, data) {
        if (err) throw err;

        console.log(JSON.stringify(doc));
        db.close();
    });
});

Thanks @jenovs