How to call mongodb collection getall by node.js? - javascript

I wanna take the whole list of notifies from mongo db but it returns empty([]) array also I know that i need callback or shorter way of it . Do you have any idea for collecting any data from mongodb by node.js? If I call this /Notifies method (http://127.0.0.1:5000/Notifies)
var MongoClient = require('mongodb').MongoClient;
var express = require("express");
var app = express();
format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) {
throw err;
} else {
console.log("successfully connected to the database");
}
db.close();
});
app.get('/Notifies', function (req, res) {
// BAD! Creates a new connection pool for every request
console.log('connected');
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) throw err;
var coll = db.collection('Notifies');
var arr = [];
coll.find({}, function (err, docs) {
docs.each(function (err, doc) {
if (doc) {
console.log(doc);
arr.push(doc);
} else {
res.end();
}
});
});
return res.json(arr);
});
});
var port = Number(process.env.PORT || 5000);
app.listen(port, function () {
console.log("Listening on " + port);
})

Don't use for docs.each instead of this use .toArray so it will return directly a array and then use Json.stringify to convert it into json string array
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) throw err;
var coll = db.collection('Notifies');
coll.find({}).toArray(function (err, result) {
if (err) {
res.send(err);
} else {
res.send(JSON.stringify(result));
}
})
});

The problem is you are returning the empty array from within the function, before the actual DB operation occurs. You need to move the line return res.json(arr);
into the find function:
app.get('/Notifies', function (req, res) {
// BAD! Creates a new connection pool for every request
console.log('connected');
MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) {
if (err) throw err;
var coll = db.collection('Notifies');
var arr = [];
coll.find({}, function (err, docs) {
console.log(docs);
docs.each(function (err, doc) {
if (doc) {
console.log(doc);
arr.push(doc);
} else {
res.end();
}
});
return res.json(arr);
});
});
});
Also, for future use, do not reuse variable names in nested functions (you have 3 functions that use the variable err).

Related

In nodejs collection.find() is not fetching values from Mongodb collection.It returning nothing

app.get('/render', function(req, res) {
MongoClient.connect(dburl, function(err, db) {
if (err) throw err;
var collection = db.collection('shopping_list');
collection.find().toArray(function(err, result) {
res.send({result :result});
});
db.close();
});
});
In nodejs collection.find() is not fetching values from Mongodb collection.It returning nothing
In nodejs collection.find() is not fetching values from Mongodb collection.It returning nothing
exports.index = function(req, res) {
var queryObj = {};
UserModel.find(queryObj)
.exec(function(err, users) {
if (!users) {
console.log("users not found");
}
if (!err) {
console.log("number of users",users.length);
} else {
console.log("err",err);
}
});
};

Node.js doesn't show results status properly in api

I'm developing a simple rest API in Node.js, and it works middling.
This is my controller code:
...
exports.listById = function(id, callback) {
Course.findById(id, function(err, courses){
if(err){
callback({error: 'Not Found'});
}
else{
callback(courses);
}
});
}
And this is my route:
app.get('/courses/:id', function(req, res){
var id = req.params.id;
courseController.listById(id, function(resp){
res.status(200).json(resp);
});
});
This code works and show results of my collection in mongodb.
But the code below, doesn't show results with postman:
app.get('/courses/:id', function(req, res){
var id = req.params.id;
courseController.listById(id, function(err, resp){
if(err){
res.status(404).send(err);
}
else{
res.status(200).json(resp);
}
});
});
exports.listById = function(id, callback) {
Course.findById(id, function(err, courses){
if(err)
return callback(new Error('Not Found')); // You must return Error by standard
callback(null, courses); // You must set first argument (error) to null
});
}
...
// You can check that id is number
app.get('/courses/:id(\\d+)', function(req, res, next) {
var id = req.params.id;
courseController.listById(id, function(err, resp) {
if(err)
return next(err); // Pass error to error-handler (see link below)
res.status(200).json(resp);
});
Best practice for callback function is first argument as error and second as result.You should
exports.listById = function (id, callback) {
Course.findById(id, function (err, courses) {
if (err) {
callback(error);
}
else {
callback(null, courses);
}
});
}
while your route should look like this:
app.get('/courses/:id', function (req, res) {
var id = req.params.id;
courseController.listById(id, function (error, courses) {
if (error) return res.status(500) // internal server error
// if I remember correctly, sources is empty array if course not found
res.status(200).json(resp);
});
});

nodejs mongodb not deleteing based on id

Can you please help me with this code. This code is not deleting the value from MongoDB, while I am running this url : http://localhost:3000/delete/57c6713455a6b92e105c5250.
I am getting this response: {"lastErrorObject":{"n":0},"value":null,"ok":1}, but not deleting .
app.get('/delete/:id', (req, res) => {
var uid = req.params.id;
db.collection('quotes').findOneAndDelete({'_id': uid}, (err, result) => {
if (err) return res.send(500, err);
res.send(result);
});
});
In MongoDB you query a document id(_id) by using the ObjectId constructor and not the ObjectId's string. Thus the query needs to be: { '_id': ObjectId(uid) }.
Example
var mongoClient = require('mongodb').MongoClient;
//Include ObjectId
var ObjectId = require('mongodb').ObjectID;
mongoClient.connect("Your connection string", function(err, db) {
var query = {
_id: ObjectId("id_string") // Important to notice
};
var collection = db.collection('your collection');
collection.find(query, function(err, docs) {
console.log(err, docs);
});
});
Suggestion
//Include ObjectId
var ObjectId = require('mongodb').ObjectID;
app.get('/delete/:id', (req, res) => {
var uid = req.params.id;
//Add object id to query object
db.collection('quotes').findOneAndDelete({'_id': ObjectId(uid)}, (err, result) => {
if (err) return res.send(500, err);
res.send(result);
});
});
Yes. thank you i figured where i did wrong. see below correct answer.
var ObjectId = require('mongodb').ObjectID;
app.get('/delete/:id', (req, res) => {
var uid = req.params.id;
db.collection('quotes').findOneAndDelete({'_id': ObjectId(uid) }, (err, result) => {
if (err) return res.send(500, err);
res.send(result);
});
});
This response means, your query is executing properly "OK":1, but the find query is unable to find any doc to delete it.
So before using "findOneAndDelete" use only "findOne" and log the response to check weather you that doc or not.

NodeJS mongo .find is not a function

I'm implementing a little server application with node.js and ran in a problem, where the collection.find() method is not recognized.
Here is my code:
// THIS FUNCTION WORKS CORRECTLY
var find_all_seasons = function (callback) {
var season_collection = db.get().collection('season_collection');
// Find some documents
season_collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
console.log(docs)
callback(docs);
});
};
// HERE I ALWAYS GET THE EXCEPTION
var find_speaker_by_name = function (name, callback) {
var speaker_collection = db.get().collection('speaker_collection').find({"name":name})(function(err, doc) {
assert.equal(err, null);
console.log("Found the following records");
console.log(doc.name)
callback(doc);
});
};
........
app.get('/api/speakers/:name', function (req, res) {
var name = req.params.name;
find_speaker_by_name(name, function (err, result) {
if (err)
res.send(err);
res.json(result);
})
});
Exception:
TypeError: db.get(...).collection(...).find(...) is not a function
at find_speaker_by_name
My DB Connection:
var MongoClient = require('mongodb').MongoClient
var state = {
db: null
};
exports.connect = function(url, done) {
if (state.db) return done();
MongoClient.connect(url, function(err, db) {
if (err) return done(err);
state.db = db;
done()
})
};
exports.get = function() {
return state.db
};
exports.close = function(done) {
if (state.db) {
state.db.close(function(err, result) {
state.db = null
state.mode = null
done(err)
})
}
};

Upload an image from a client-side webpage

One of the modules in our project is to upload an image from a webpage to mongo database using nodejs. We have completed connecting to a mongo database and upload an image using physical location of the image on the system, but we are not able to make the upload dynamic from a webpage.
We convert the image to a base64 code and then save it to the database. MongoDB returns a unique id. We want to integrate this process and make it dynamic. The code we used to connect to mongoDB and upload an image from physical location is available here.
var MongoClient = require('mongodb').MongoClient,
format = require('util').format,
fs = require('fs'),
http = require('http');
http.createServer(function (req, res) {
//should be triggered by the user upload button
put();
//triggered after the upload/button click
res.writeHead(200, {'Content-Type': 'text/html'});
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) throw err;
var collection = db.collection('test_insert');
collection.find().toArray(function(err, results) {
//console.dir(results);
// Let's close the db
//ret = results[0];
console.log(results[0]);
res.end('<img alt="sample" src="data:image/png;base64,' + results[0].image + '">');
db.close();
});
});
//res.end("Hello World\n");
}).listen(3030);
function read() {
var image_base64 = fs.readFileSync('./uploads/2088-1nqsb3l.jpg').toString('base64');
return image_base64;
//console.log(base64_data);
}
function put() {
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) throw err;
var collection = db.collection('test_insert');
collection.insert({image: read()}, function(err, docs) {
console.log("data inserted");
db.close();
});
});
}
function get() {
var ret;
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) throw err;
var collection = db.collection('test_insert');
collection.find().toArray(function(err, results) {
//console.dir(results);
// Let's close the db
ret = results[0];
db.close();
});
});
return ret;
}
/*
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) throw err;
var collection = db.collection('test_insert');
collection.insert({a: base64_data}, function(err, docs) {
collection.count(function(err, count) {
console.log(format("count = %s", count));
});
// Locate all the entries using find
collection.find().toArray(function(err, results) {
console.dir(results);
// Let's close the db
db.close();
});
});
});
*/
You have to send the image via XMLHttpRequest from the client to nodejs. Then store it in mongo like you did with the file, you read by fs.readFileSync.

Categories