Getting error while connecting to mongo in aws lambda - javascript

I am trying to connect to mongo database using mongodb but its throwing error unable to resolve.
This is my mongo connect fucntion
const {
MongoClient,
ObjectId,
} = require('mongodb');
const {
MERCURY_MONGO_DB_URL,
} = process.env;
const initialize_mongodb_database_connection = async () => {
//
// Create a new MongoClient
//
const connection = new MongoClient(MERCURY_MONGO_DB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Use connect method to connect to the Server
connection.connect((err) => {
if (err != null) {
console.log(`MongoDB Connection :: Error :: ${err}`);
process.exit(1);
} else {
const db = connection.db('demo');
return db;
global.ObjectId = ObjectId;
console.log('MongoDB Connection :: Ready');
}
});
};
module.exports = {
initialize_mongodb_database_connection,
};
And this is where I am trying to use it but getting error
var db = await initialize_mongodb_database_connection();
const data = await db.collection(`access_log_${result.student_uuid}`)
.find(where)
.toArray();
console.log(data)
I am getting error of this Cannot read property 'collection' of undefined
where actually I have data at collection access_log_1747386c-9577-4073-b818-649db0ce9d50
not sure why it isn't working? I have that collection in my db.
Can any one help here? Also I am developing this for aws lamdba

The error message is saying the db object is undefined. When looking at your initialize_mongodb_database_connection function, you're not returning the promise returned by MongoClient#connect.
const initialize_mongodb_database_connection = async () => {
...
return connection.connect((err) => {
...
});
};

Related

Show results mongodb nodejs

i need show result in my database mongodb.
Im use mongodb.cloud atlas i already created database now i need show result in my database
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://test:test#cluster0.bvhvj.mongodb.net/*****?
retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("sample_restaurants");
// perform actions on the collection object
// need show result database in console.log
client.close();
});
Im expected result in sample_restaurants.restaurants in console.log
EDIT
Im use your answer but my problème return error
MongoError: no primary server available
this code
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://test:test#cluster0.bvhvj.mongodb.net/****?
retryWrites=true&w=majority";
client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("sample_restaurants").
collection("restaurants").find({}).toArray(function(err,result)
{
if(err) throw err;
console.log(result)
});
});
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://test:test#cluster0.bvhvj.mongodb.net/*****?
retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("sample_restaurants").
collection("restaurants").find({}).toArray(function(err,result)
{
if(err) throw err;
console.log(result)
});
});
First improve your code to fix the error:
let db = await MongoClient.connect(MONGO_URI, { useNewUrlParser: true });
db = await db.db();
const collection = db.collection('sample_restaurants');
You have two different ways to get the data.
1- If your results are not a lot, you can get all of them in once and then print them.
const results = await collection.find({}).toArray();
console.log(results)
2- If the number of the records is something like 2 million records, you can not use it this way. Have to create a cursor and then get them one by one.
const cursor = collection.find();
while(await cursor.hasNext()) {
const record = await cursor.next();
console.log(record);
}

Why is my callback not working correctly?

This method runs at node server
const express = require("express");
const app = express();
const fs = require("fs");
const connectDb = require("./config/db");
const __init__ = (local = false) => {
fs.writeFile(
"./config/default.json",
`{
"mongoURI": ${
local
? `"mongodb://127.0.0.1:27017/test"`
: `"mongodb+srv://admin:<password>#abc-xxghh.mongodb.net/test?retryWrites=true&w=majority"`
}
}`,
function(err) {
if (err) {
return console.log(err);
}
connectDb();
}
);
};
__init__(true);
The problem is that if originally mongoURI: 127.0.0.1:27017, and if I do __init__(false), Node will try to connect to 127.0.0.1:27017, when it should be connecting to +srv uri.
If I run __init__(false) AGAIN, then it will connect to appropriate link.
Likewise, if I then run __init__(true), it will connect to srv+ when it should be connecting to local, and if I run __init__(true) again, only then it will connect to local.
What am I doing wrong here? I'm using the callback as Im supposed to, no?
Edit:
//config/db
// for mongoDB connection
const mongoose = require("mongoose");
// require the directory
const config = require("config");
// get all contents of JSON file
const db = config.get("mongoURI");
const connectDb = async () => {
try {
console.log("connecting to mongodb", db);
await mongoose.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
});
console.log("Mongo DB connected");
} catch (err) {
console.log("unable to connect to mongodb");
console.log(err.message);
//exit if failure
process.exit(1);
}
};
module.exports = connectDb;
I've even tried doing the following:
.....
console.log("Developing locally:", local);
// require the directory
const config = require("config");
// get all contents of JSON file
const db = config.get("mongoURI");
connectDb(db);
.....
But it still reads the old value
The problem is on execution order since the require is sync
The order now is:
const connectDb = require("./config/db");
const config = require("config");
const db = config.get("mongoURI"); // this has the OLD VALUE
fs.writeFile(...
await mongoose.connect(db, { // this is using the OLD REFERENCE
So you need to change your connectDb function like this:
const connectDb = async () => {
const config = require("config");
// get all contents of JSON file
const db = config.get("mongoURI");
try {
console.log("connecting to mongodb", db);
await mongoose.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
});
console.log("Mongo DB connected");
} catch (err) {
console.log("unable to connect to mongodb");
console.log(err.message);
//exit if failure
process.exit(1);
}
};
Anyway, I think this is not a nicer way to load config based on the environment, so I would suggest improving it using factory pattern.
Your code for URL local vs srv+ is correct. Problem i could see is placement of method connectDb();
fs.writeFile("fir arg - URL", "second -content", third - error fun {});
where in your code after function, connectDb() is placed after error fun. After it should be closed.

I am having trouble connecting my app to Mongo Atlas

I am following the documentation and based off what I read I am doing it right. I am connecting to my Mongo Atlas server. The server connects and I am able to connect to the DB and the Collection. Yet the DB and the Collection are not being passed to the db object.
I have tried console logging the values and refactored my logic and yet still no solution.
// MongoDB Connection Setup
let db = {};
let MongoClient = require("mongodb").MongoClient;
let uri = process.env.MONGODB_CONNECT_URL;
let client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
assert.strictEqual(null, err);
console.log('Connected Successfully to MongoDB!');
db.client = client.db("cosmosdb");
db.collection = client.db('cosmosdb').collection('cosmos');
console.log("Database Values: ", db) // This actually returns values
return db;
});
console.log('Database: ', db); // Not returning values
app.set('port', process.env.PORT || 3000);
let server = app.listen(app.get('port'), () => {
console.log(`Express server listening on port: `, server.address().port)
});
server.db = db;
When I console.log db I am expecting to see
Database: {
client: // values
collection: // values
}
yet this is what I am getting back
Database: {}
EDITED
Is your uri assigned like below? (mongodb+srv)
let uri = `mongodb+srv://${dbUser}:${dbPwd}#${dbHost}/test?retryWrites=true`;
let client = new MongoClient(uri, { useNewUrlParser: true });
There is a parameter you are missing on the connect() call, you have "err", but it should be (err, client). So for me it looks as follows:
var db = {};
var MongoClient = require('mongodb').MongoClient;
//Use connect method to connect to the Server
MongoClient.connect(process.env.MONGODB_CONNECT_URL, { useNewUrlParser: true }, function (err, client) {
assert.equal(null, err);
db.client = client;
db.collection = client.db('newswatcherdb').collection('newswatcher');
console.log("Connected to MongoDB server");
});

How to get data from MongoDB with mongoose

I am writing CLI in which user can get any collection from MongoDB by entering the name of this connection to the console.
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const db = mongoose.connect('mongodb://paito:-----mlab.com:22222/paito', { useNewUrlParser: true });
const getCollection = (collection) => {
db.getCollection(collection)
.exec((err, data) => {
// assert.equal(null, err);
console.info(data);
console.info(`${data.length} matches`);
db.close();
})
};
module.exports = {
getCollection
};
I need to get this data to the console. The actual error "TypeError: db.getCollection is not a function".

Every second run throws: MongoError: Topology was destroyed

I am building a REST API but every second time I load my site I get a MongoError: Topology was destroyed. Can someone help me fixing this? I have a feeling that there is something wrong with the asynchronous running.
const client = new MongoClient(apiconfig.mongoUrl, {
useNewUrlParser: true
});
app.get("/api/:object", (req, res) => {
mongodb(req.params["object"], async (collection: Collection) => {
if (collection !== undefined) {
let result = await collection.find().toArray();
res.send(result);
}
else {
res.sendStatus(404);
}
});
});
const mongodb = (coll: string, operation: (collection: Collection) => Promise<void>) => {
client.connect((err) => {
const db = client.db("VaorraJS");
db.collections().then((collections) => {
operation(collections.find((collection) => collection.collectionName === coll)).then(() => {
client.close();
});
}).catch((error) => {
console.log("ERROR: " + error);
});
});
}
app.listen(5000);
I would suggest the use Mongoose
you are creating DB connection for every request, which is not the correct way
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = '<some db>';
// Use connect method to connect to the server
let db;
MongoClient.connect(url, function (err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
db = client.db(dbName);
});
app.get("/api/:object", async(req, res) => {
const collection = db.collection(req.params["object"]);
let result = await collection.find().toArray();
res.send(result);
});

Categories