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
});
Related
I am trying to return all the entries from a mongodb collection from a nodejs.
I had written the function and it works if i console log the result i see all the objects from the colletion, but if i try to return the result i am getting undefined.
I cant figure it out why? I had also tried to JSON stringify and JSON parse after but still no success.
Here is my code:
`
const mongoUrl = "mongodb://192.168.8.156:27017/";
const getRoomReadings = function (id) {
MongoClient.connect(mongoUrl, function (err, db) {
if (err) throw err;
let dbo = db.db(`room${id}`);
dbo
.collection("env")
.find({})
.toArray(function (err, result) {
if (err) throw err;
return result;
});
});
};
// API RoomX route
app.get("/api/r:id", (req, res) => {
const rez = getRoomReadings(req.params.id);
console.log(rez);
});
`
I am using nodejs with express.
Please help me. Thanks in advance.
I had also tried to JSON stringify and JSON parse after but still no success.
I don't know why you created the connection each time you do the request but using promises will help you.
Example:
const mongoUrl = "mongodb://192.168.8.156:27017/";
const getRoomReadings = function (id) {
return new Promise((res, rej) => {
MongoClient.connect(mongoUrl, function (err, db) {
if (err) rej(err);
let dbo = db.db(`room${id}`);
dbo
.collection("env")
.find({})
.toArray(function (err, result) {
if (err) rej(err);
return res(result);
});
});
})
};
// API RoomX route
app.get("/api/r:id", async (req, res) => {
const rez = await getRoomReadings(req.params.id);
console.log(rez);
});
a better way to create a connection it creating a file call conn.js and inside that file create your connection
const { MongoClient } = require("mongodb");
const connectionString = process.env.ATLAS_URI;
const client = new MongoClient(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
let dbConnection;
module.exports = {
connectToServer: function (callback) {
client.connect(function (err, db) {
if (err || !db) {
return callback(err);
}
dbConnection = db.db(<db_name>);
console.log("Successfully connected to MongoDB.");
return callback();
});
},
getDb: function () {
return dbConnection;
},
};
initialize the connection and use getDb to get the connection
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
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();
}
});
};
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);
I am using MongoDB to insert a record into the database, every time the post method is called. I know I do not want to connect to the db inside of the post function every time, but this is giving me errors? How can I correct this?
var mongo = require('mongodb');
var url = 'mongodb://localhost:27017/Wedding'
var db = function() {
mongo.connect(url, function(err, db){
if (!err){
return db;
}
});
}
app.post('/rsvp', function (req, res) {
var item ={
name: req.body.name,
attending: req.body.attending,
};
insertItem(item);
res.sendFile(path.join(__dirname + '/confirm.html'));
})
function insertItem(item){
db.collection('rsvpList').insertOne(item, function(err, result){
assert.equal(null, err);
})
}
I am getting this error:
TypeError: Object function () {
mongo.connect(url, function(err, db){
if (!err){
return db;
}
});
} has no method 'collection'
at insertItem (C:\Users\A587092\Documents\weddingWebsite\server.js:53:8)
at app.listen.host (C:\Users\A587092\Documents\weddingWebsite\server.js:38:4)
at Layer.handle [as handle_request] (C:\Users\A587092\Documents\weddingWebsite\node_modules\express\lib\router\layer.js:95:5)
The problem is your db does not point to the Mongo instance rather to a function!
Try this -
var mongo = require('mongodb');
var url = 'mongodb://localhost:27017/Wedding'
var db;
mongo.connect(url, function(err, connectedDB){
if (!err){
db = connectedDB;
}
});
You couldn't simply return a value from an asynchronous method:
You should use a callback function:
var connectDb = function(url, cb) {
mongo.connect(url, function(err, db){
if ( err ) {
cb( err );
}
cb(null, db);
});
};
Usage:
function insertItem(item) {
connectDb(url, function(error, db) {
if ( error ) {
throw error;
}
db.collection('rsvpList').insertOne(item, function(err, result) {
assert.equal(null, err);
});
});
}
Or a promise:
var connectDb = function(url) {
return new Promise(function(resolve, reject) {
mongo.connect(url, function(err, db){
if ( err ) {
reject(err);
}
resolve(db);
});
});
};
Usage:
function insertItem(item) {
connectDb(url)
.then(function(db) {
db.collection('rsvpList').insertOne(item, function(err, result) {
assert.equal(null, err);
});
}, function(err) {
throw err;
});
}
I change the function name from db to connectDb because we want to connect to db and then doing something after connecting. and this way your code reads well.
Also note that here also your insertItem function doing an asynchronous task so if you need the result outside of this function you should implement a similar approach, i leave it to you ;)