Why is `func` not a function here in node.js? - node.js

I am learning mongodb, and in the book, there's a code
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://127.0.0.1:27017/testdb";
module.exports = function (func) {
MongoClient.connect(url, function(err, db) {
if (err) throw err;
else {
console.log("connected");
func(db);
db.close();
}
});
};
I run this code, but throw the error TypeError: func is not a function, I googled, but lots of codes like this, my mongodb version is 4.0, and node.js version is 9.10, any ideas?

Whatever func you are passing must be a function.
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://127.0.0.1:27017/testdb";
module.exports = function (func) { //func must be function, dont pass just a variable
MongoClient.connect(url, function(err, db) {
if (err) throw err;
else {
console.log("connected");
func(db);
db.close();
}
});
};

Related

Mongodb find not printing json data

In the code I am trying to find all documents with code UE19CS204.But in the console.log
a big message is printed not the JSON data.The findOne() is working but not find().
I don’t know what change to do to find all documents with code UE19CS204.
var MongoClient = require(‘mongodb’).MongoClient;
var url = “mongodb://localhost:27017/”;
MongoClient.connect(url, { useUnifiedTopology: true } ,function(err, db) {
if (err) throw err;
var dbo = db.db(“pes”);
dbo.collection(“course”).find({“code”:“UE19CS204”}, function(err, result) {
if (err) throw err;
console.log(result);
});
dbo.collection(“course”).findOne({code:“UE19CS204”}, function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
The method find() creates a cursor for a query that can be used to iterate over results from MongoDB, see here.
Use toArray(), you can finde the documentation here.
dbo.collection(“course”).find({“code”:“UE19CS204”}).toArray(function(err, docs) {
if (err) {
throw err;
}
console.log(docs);
})
Full example:
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'pes';
// Collection Name
const collectionName = 'course';
// Filter
const filter = { 'code': 'UE19CS204' }
// Use connect method to connect to the server
MongoClient.connect(url, { useUnifiedTopology: true }, function(err, client) {
if (err) {
throw err;
}
client.db(dbName).collection(collectionName).find(filter).toArray(function(err, docs) {
if (err) {
throw err;
}
console.log(docs);
})
client.close();
});

How to use a variable outside a callback in Node JS?

I'm impractical with node js. I have the following code:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("test").findOne(
{},
{ sort: { _id: -1 } },
(err, data) => {
console.log(data);
},
);
db.close();
});
I would like to use the variable "data" outside the scope of MongoClient.connect (). The problem should be that a callback function is used and is therefore executed asynchronously.
If I do something like this:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var x;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("test").findOne(
{},
{ sort: { _id: -1 } },
(err, data) => {
console.log(data);
x = data;
},
);
db.close();
});
console.log(x);
The result of x will be "undefined".
How can this problem be solved in general? How do you use variables outside of a certain scope in order to execute the code in a pseudo-synchronous manner?
you can use async and wait to convert this asynchronous code to synchronous code,
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var x;
(async ()=>{
await MongoClient.connect(url, (err, db) => {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("test").findOne(
{},
{ sort: { _id: -1 } },
(err, data) => {
console.log(data);
x = data;
},
);
db.close();
});
})();
console.log(x);
to learn more,
https://tylermcginnis.com/async-javascript-from-callbacks-to-promises-to-async-await/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

NodeJS - Image displayed from MongoDB as an empty square

I want to store an image in MongoDB using NodeJS. I have managed to insert an image in database, as an object with Buffer and img parameters. However, when I display it, I get an empty square instead. Anyone knows how to fix this?
Code :
var imgPath = '.public/images/image.png';
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
const assert = require('assert');
const dbName = 'database';
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
var collectionClient = db.collection('collection1');
var store = {
img: {
data: Buffer,
contentType: String
}
};
store.img.data = fs.readFileSync(imgPath);
store.img.contentType = 'image/png';
collectionClient.insertMany([store], function (err, result) {
if (err) {
console.error('Insert failed', err);
} else {
console.log('Insert successful');
}
});
});
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("database");
dbo.collection("collection1").find({}).toArray(function(err, result) {
if (err) throw err;
router.get('/', function(req, res, next) {
res.contentType(result[0].img.contentType);
res.send(result[0].img.data);
});
db.close();
});
});
Instead, try this:
const download = Buffer.from((result[0].img.data).toString('utf-8','base64'));
res.end(download);

Wait until MongoDB has completed its query without using callbacks

I have an issue with the asynchrous programming model in Node.js.
I know this has been asked before, but so far I haven't found anything that I can use to solve my issue.
How do I force console.log from running before dbQueryName has been invoked and username has gotten its value from it?
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
function dbQueryName() {
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("users").findOne({}, function(err, result) {
if (err) throw err;
return result.name
db.close();
});
});
}
var username = dbQueryName();
// Wait until dbQueryName() has been invoked and username has gotten its value before running this
console.log(username);
I have managed to get it working using a callback parameter in the function, but is there a way to do this with less code and indentation?
function dbQueryName(callback) {
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("users").findOne({}, function(err, result) {
if (err) throw err;
callback(result.name)
db.close();
});
});
}
dbQuery(function(result){
var username = result
console.log(username);
});
Yes if you are not passing a callback to MongoClient.connect or collection.findOne, it returns a promise.
But you need to add another function to use async await
init()
async function dbQueryName() {
const db = await MongoClient.connect(url);
const dbo = db.db("mydb");
const user = await dbo.collection("users").findOne({})
return user.name
}
async function init() {
try {
const name = await dbQueryName()
} catch (error) {
console.log(error);
}
}

nodejs export variable from function

I want to export variable 'result_array' from './models/devices-client.js' below
var config = require('./config');
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect(config.dbadmin_uri, function (err, db) {
if (err) throw err;
// console.log('Successfully connected');
var collection = db.collection('repvpn2');
collection.find().toArray(function (err, result_array) {
// console.log('Found results:', result_array);
module.exports.Hosts = result_array;
db.close();
});
});
but when import in the other file it prints 'undefined' ?
var Hosts = require('./models/devices-client').Hosts;
console.log(Hosts);
let your module take an async function callback.
// JavaScript source code
var config = require('./config');
var MongoClient = require('mongodb').MongoClient;
module.exports = function (callback) {
MongoClient.connect(config.dbadmin_uri, function (err, db) {
if (err) throw err;
// console.log('Successfully connected');
var collection = db.collection('repvpn2');
collection.find().toArray(function (err, result_array) {
// console.log('Found results:', result_array);
callback(err, result_array);
db.close();
});
});
}
require('./models/devices-client')(function callback(err,Hosts) {
//Hosts Here
});

Resources