javascript - Mongodb insert callback never called -
this question followup of this one , figured better ask new question post comment , necropost.
(tl;dr give solution _id when collection inserted)
i've tried .js bash script or in console doesn't seem work :
var latest; db.collec.insert({test:"yes"},function(err,newdoc){ latest = newdoc[0]._id; });
the variable doesn't change. in console command returns writeresult({ "ninserted" : 1 })
lastest still void, , in js has same value before.
is there way id without node.js ? should switch node.js ?
my bash script mongo --eval '<my whole javascript>'
you missing 1 piece in expression.
var latest; db.collec.insert({test:"yes"},function(err,newdoc){ latest = newdoc.ops[0]._id; });
newdoc
contains entire response mongo.
newdoc.ops
contains array of inserted row(s).
newdoc.insertedids
contains array of id's of inserted row(s).
an alternative solution be:
var latest; db.collec.insert({test:"yes"},function(err,newdoc){ latest = newdoc.insertedids[0]; });
you can data without using node.js. can use mongodb shell. command prompt on system running mongo type mongo
interactive shell. once there, run mongo commands:
> show dbs //will list databases > use dbname //will use database called dbname > show collections //will list collections within current database > db.col.find({test: 'yes'}); //will retrieve document collection named col '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 used query _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
Post a Comment