Teleporting Goat Teleporting Goat - 12 days ago 10
Javascript Question

Mongodb insert callback never called

This question is a followup of this one and I figured it was better to ask a new question than to post a comment and necropost.

(TL;DR they give a solution to get the _id when a collection is inserted)

I've tried with a .js bash script or in console it doesn't seem to work to do :

var latest;
db.collec.insert({test:"yes"},function(err,newDoc){
latest = newDoc[0]._id;
});


The variable doesn't change. In console the command returns
WriteResult({ "nInserted" : 1 })
but lastest is still void, and in js it has the same value as before.

Is there a way to get the id without Node.js ? Should I switch to Node.js ?




My bash script is really just
mongo --eval '<my whole javascript>'

Answer

You are missing one piece in your expression.

var latest;
db.collec.insert({test:"yes"},function(err,newDoc){
    latest = newDoc.ops[0]._id;
});

newDoc contains the entire response from mongo.

newDoc.ops contains an array of the inserted row(s).

newDoc.insertedIds contains an array of the ID's of the inserted row(s).

An alternative solution would be:

var latest;
db.collec.insert({test:"yes"},function(err,newDoc){
    latest = newDoc.insertedIds[0];
});

You can get the data without using Node.js. You can use the Mongodb shell. From the command prompt on the system running Mongo type mongo to get to the interactive shell. Once there, run Mongo commands:

> show dbs  //will list all databases
> use dbName  //will use database called dbName
> show collections  //will list all collections within the current database
> db.col.find({test: 'yes'});  //will retrieve document from collection named col where 'test' = 'yes'

Entire working JavaScript file:

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

mongodb.connect('mongodb://localhost:27017/testDb', function(err, db){
   var collection = db.collection('collec');
   collection.insert({'test': 'yes'}, function(err, results){
      console.log(results.ops[0]._id);
      db.close();
   });
});

This can be used to query by the _id directly.

var mongodb = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectID;

mongodb.connect('mongodb://localhost:27017/testDb', function(err, db){
   var collection = db.collection('collec');
   var id = ObjectId('583346693b3b904546ca175d');
   collection.find({'_id': id}).toArray(function(err, results){
      console.log(results);
      db.close();
   });
});
Comments