node js mongo find last inserted - node.js

I am having a hard time trying to find the last inserted element into mongo. I am using an example code I found and trying to make the query and display the item but I am getting an error. I understand I am suppose to do something like this.
db.collectionName.findOne({}, {sort:{$natural:-1}})
But this is what I have so far and it's not working.
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(err) { return console.dir(err); }
var collection = db.collection('test');
var doc1 = {'hello':'doc1'};
var doc2 = {'hello':'doc2'};
var lotsOfDocs = [{'hello':'doc3'}, {'hello':'doc4'}];
collection.insert(doc1);
collection.insert(doc2, {w:1}, function(err, result) {});
collection.insert(lotsOfDocs, {w:1}, function(err, result) {});
collection.find({}).toArray(function(err, docs) {
console.log(docs[0]);
});
db.close();
});
This is the error.
nodejs/node_modules/mongodb/lib/mongodb/connection/base.js:246
throw message;
^
TypeError: Cannot read property '0' of null
I checked to make sure the database is not empty so I am not sure why it's returning null.

I've found a possible solution(here) to your problem. It might be due to the fact that the database connection closes before the operations that you have issued finish.
You can fix it by including the db.close() call inside the find query.
collection.find({}).toArray(function(err, docs) {
console.log(docs[0]);
db.close();
});

Related

getting specific item from query answer mongodb node

I was wondering if there is a way I can get a part of an object in mongo using node. For example, it would be great if I could log say the email that is being added, by using something like console.log(result.email) to get the email part of my response. Does anyone know how to do this?
Ok so I have found a way to do this. It will not work on the .find function for some reason, but will work on .findOne and .sort
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("db");
let query = {
username: "username",
key: "key"
};
dbo.collection("keys").findOne(query, (function(err, result) {
var lengthboi = result.length;
console.log(result)
if (lengthboi === 1) {
//do stuff
} else {
}
}));
});

mongodb in nodejs return undefined when trying to connect to collection

when I write this code below I get:
Connected correctly to DB
undefined
undefined
I have collection named users, so this sould not happened... why is the happening?
Thanks
var url = 'mongodb://user:pass#ds023475.mlab.com:23475/small-talkz';
MongoClient.connect(url, function(err, db) {
if (err) {
console.log(err);
return db.close();
}
console.log("Connected correctly to DB.");
// update a record in the collection
console.log(db.collection("users"));
console.log(db.users);
return db.close();
});
I would say you need to .find() what it is you want from the collection. However, it is strange that it returns undefined. Try this code:
var MongoClient = require('mongodb').MongoClient, format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) throw err;
db.collectionNames(function(err, collections){
console.log(collections);
});
});
to see what collection names the current database has. Perhaps it doesn't exist?
Otherwise, try finding the collection elements, as shown in the docs example.

Error When Retrieving Multiple Collections in Mongo/Express/Node

I am building a page which needs to retrieve and list data from several different Mongodb collections. I've been doing separate queries in the Express router function then bunging the results into an array which is passed to the page where the relevant data for each section are accessed. This has worked ok so far with up to three queries, but, if I add a fourth query I get an error.
The router function looks like this:
router.get('/thetest',function(req,res){
var finalResult = {};
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/myapp';
MongoClient.connect(url, function(err, db){
if(err){
console.log("Connection Error",err);
}else{
var collection = db.collection('cats');
collection.find({}).toArray(function(err,result){
if(err){
console.log("Error retrieving cats");
}else if (result.length){
finalResult.ctlist = result;
console.log("cats OK");
}
});
var collection = db.collection('mice');
collection.find({}).toArray(function(err,result){
if(err){
console.log("Error retrieving mice");
}else if (result.length){
finalResult.mclist = result;
console.log("mices OK");
}
});
var collection = db.collection('cheese');
collection.find({}).toArray(function(err,result){
if(err){
console.log("Error retrieving cheese");
}else if (result.length){
finalResult.chlist = result;
console.log("Cheese OK");
}else{
console.log('No Documents');
}
});
var collection = db.collection('mice');
collection.find({}).sort({tailLength:1}).limit(3).toArray(function(err,result){
if(err){
console.log("Error retrieving alert bookings");
}else if (result.length){
finalResult.mtlist = result;
console.log("Mouse tail length ok");
res.render('thetest',{
"thelist":finalResult
});
}
db.close();
});
}
});
});
(using dummy collection names)
So, there are four queries made to three different collections. The results are listed in a Jade template using an each loop.
If I comment out any one of the four queries and just run the other three it works fine: the results are listed on the page. If I uncomment and run all four queries then Node will choke and, obviously, nothing is listed on the page. None of the collections are above about half a dozen documents in size with a handful of fields in each.
I'm pretty new to all this and I understand that this may not be the best way to do what I am attempting.
Can anybody a) explain where I'm going wrong and/or b) suggest a better approach?
Thanks
I think the problem is due to your code.
Node.js is an asynchronous programming language, so all the operations works parallely.
In your code 'db.close();' close the database connection. For eg. if all the db operation works parallely and the 4th one (in your code) execute firstly then it close the database connection. So it is not a good programming style.
So you can use 'async' library for solving this.
https://github.com/caolan/async
Sample code :
async.parallel([
function(callback){
dbOperation1(query, callback);
},
function(callback){
dbOperation2(query2, callback);
},
function(callback){
dbOperation3(query3, callback);
},
function(callback){
dbOperation4(query4, callback);
}
],
function(err, results){
if (err) {
renderError(err);
} else {
renderHTML(results[0], results[1], results[2], results[4]);
}
});
If you comment all four condition then I am pretty sure that you are commenting res.render('thetest',{
"thelist":finalResult
});
Hence code is chocked. Because express API always wait for response and if you not provide response sentence, then for some time is going to wait and then crash out.
Solution : You must write your response statement out of condition.

Storing Collection result from mongoDB in Node

I am new to node and I have read the data from mongoDB successfully.
But I would like to store the whole data from the Collection into a variable in nodejs as I would like to use them in the index page.
I do not know how to store it.
// Connection URL
var url = 'mongodb://localhost:27017/test';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
seriescollection = db.collection('series');
});
var findseries = function (db, callback) {
var cursor = db.collection('series').find();
cursor.each(function (err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
} else {
callback();
}
});
};
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
//insertDocument(db, function () {});
findseries(db, function () {
db.close();
});
});
My sample JSON object in MongoDb is
{
"_id" : "b835225ba18",
"title" : "Name",
"imageurl" :"https://promotions.bellaliant.net/files/Images/TMN/Ballers-June2015.jpg",
"namespaceId" : "UNI890"
}
I would like to access all the fields and create a page based on the fields that I have stored. I need to access all the fields and that is my main goal.
This is a pet project I am working on a leisure time to learn MEAN stack a bit.
Thanks a lot for your help!!!!
There's a few issues with this code, but I think what you're looking for is the toArray method:
var findseries = function (db, callback) {
db.collection('series').find().toArray(function(err, allTheThings) {
// Do whatever with the array
// Spit them all out to console
console.log(allTheThings);
// Get the first one
allTheThings[0];
// Iterate over them
allTheThings.forEach(function(thing) {
// This is a single instance of thing
thing;
});
// Return them
callback(null, allTheThings);
}
}
More here: https://docs.mongodb.org/manual/reference/method/cursor.toArray/
And here: https://mongodb.github.io/node-mongodb-native/api-generated/cursor.html#toarray

mongodb native how to work with query

I'm trying to retrieve data from my mongolab DB using Node-mongodb-native
var findAll = function () {
var ddocs;
collection.find({}).each(function (arr, docs) {
ddocs = docs;
});
console.log(ddocs);
};
But it seems that when I log ddocs, it will give me undefined, but if I log docs it will show me the data.
Please help
How should I use this function ?
Thanks
Tzelon Machluf
You're basically trying to create a function that will return all of the documents in a collection? If so, the below should do work. However, I agree with #hgoebl and that you should work on your understanding of node as this is not likely the best way to accomplish what you're trying to do.
var ddocs;
var findAll = collection.find().toArray( function(err, docs) {
if(err)
throw err;
console.log('Collection returned');
return ddocs = docs;
});
setTimeout( function(err) {
if(err) throw err;
console.log(ddocs);
db.close();
}, 1000);
One thing in particular to note: collection.find is asynchronous, so the problem in your code (why it says ddocs is undefined) is that you're logging ddocs before the collection.find ever finished; thus, it's initialized, but no assigned any values. The Node convention is to nest callbacks so that everything happens in the right order and when it's ready.

Resources