I'm hosting a test database on mongodb atlas, and I'm trying to connect via a simple deno app, but I keep getting the following error:
failed to lookup address information: Temporary failure in name resolution
I have made sure nothing is blocked in my firewall, and flushed my DNS to make sure it wasn't that. My code is below.
const URI = 'mongodb+srv://testUser:*password*#testdb.byjzd.azure.mongodb.net/TestDB?retryWrites=true&w=majority';
const client = new MongoClient();
await client.connect(URI).catch((err: string) => {
console.log(err);
});
Note: connecting a simple NodeJS app works fine.
Related
I am in the process of trying to connect my MongoDB to my MERN web application and was wondering the best resource for information on this type of thing. Basically, I have a MERN web app, electron desktop app, and react native mobile app that I am trying to all connect to one MongoDB, but I can't find any information on this that directly answers how it should be wired. I can provide more details if needed.
Make sure you are using the database username and password not the account username and password from Mlab.
In MLab, formerly MongoLab, do the following:
Navigate to Users
Add Database User
Choose your username and password
Now you can test this on the shell with mongo ds061374.mlab.com:61374/yourdb -u <dbuser> -p <dbpassword>.
I hope you have already signed up to mongodb and created a project there.
Below is the integration process to get your MERN application connected to MongoDB online cluster.
Make sure you have the following libraries installed dotenv, mongoose.
Create a folder in your project root directory that will hold your configuration file, Eg config_folder
Create a .js file, Eg dbConnnect.js
Create a create a dotenv file to hold the key for your MongoDB cluster by just creating a fine file on your project root folder and name it .env. NOTE no prefix required while naming this file.
login to your MongoDB and navigate to Projects, select your project then navigate to Databases -> Clusters -> connect -> connect your application -> copy the connection string.
Navigate back to your .env file and create a variable and paste the connection string as shown below.
MONGODB_URI = 'your_connection_string_from_mongoDB'
Inside dbConnect.js add the following code.
const mongoose = require('mongoose')
const dbConnect = async() => {
try {
const connected = await mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
});
console.log(`Connected ${connected.host}`)
} catch (error) {
console.log(`error : ${error.message}`)
}
}
module.exports = {
dbConnect
}
Now you need to call the above block in your server file using the code below.
const { dbConnect } = require('./config/dbConnect')
const dotenv = require('dotenv')
dotenv.config()
dbConnect();
That's the end of the integration process. It worked for me and I hope it'll help.
If you want to connect your MongoDB with the MERN app you can use the mongoose package for that, let me tell you the steps.
Packages you will need : mongoose,nodemon,express
Note*:- Make sure you know how to use Mongo Atlas.
1- Step 1- create db.js file in your main directory.
//import mongoose
const mongoose = require("mongoose")
//make connection variable
const connection = mongoose.connect("mongodb+srv://<username>:<password>#cluster0.en0mzco.mongodb.net/?retryWrites=true&w=majority")
//the username and password will be the same as your cluster username and password.
//export the connection variable
module.exports={
connection
}
2- Step 2- Create index.js file for the server
//import express
const express = require("express")
//import connection from db.js
const {connection} = require("./db.js")
//define post
const port = 4000
const app = express()
//Start server code
app.listen(port,async()=>{
try{
//mongo db all operations are done in an async manner so make sure you use async/await
await connection
//on the successful connection this msg will show in your terminal
console.log("Connected to db")
}catch(err){
console.log(err)
}
console.log("Server is runnig on port number",port)
})
3- Step 3- Make sure you add this line to your package.json inside scripts
"server":"nodemon index.js"
//Now run the server by running this command in your terminal
npm run server
Also, I am putting my youtube video for full stack web development, where you will get all the processes of how to do all the setup.
Youtube Link: Fullstack web development in 1hour
I'm facing a quite odd issue today.
I have a MongoDB database working just fine on a remote server, say 1.2.3.4, running on port 22222.
When I use the mongo cli to connect via the command line interface, everything works as expected:
mongo --host=1.2.3.4 --port=22222
But when I try to connect to the same instance using mongoose:
var options = {
server: {},
replset: {}
};
options.server.socketOptions = options.replset.socketOptions = { keepAlive: 120 };
mongoose.connect('mongodb://1.2.3.4:22222/test', options);
I get this error:
failed to connect to server [1.2.3.4:22222] on first connect
Anybody knows why?
FYI the all setup is in my company, which happens to have a corporate proxy.
I was thinking that maybe the proxy was the evil one in this case, but then why the mongo cli connection is working just fine?
Do you have a db called test? And have you tried omitting the options?
i.e. mongoose.connect('mongodb://1.2.3.4:22222/test');
I want to connect the Mongo DB on the other server with meteor on my local machine.
Any help appreciated.I am new to meteor.
error on running meteor
Can't start Mongo server. MongoDB had an
unspecified uncaught exception. This can be caused by MongoDB being
unable to write to a local database. Check that you have permissions
to write to .meteor/local. MongoDB does not support filesystems like
NFS that do not allow file locking.
On the meteor app machine, on the server side use this piece of code.
if(Meteor.isServer){
Meteor.startup(function () {
var myDatabase = new MongoInternals.RemoteCollectionDriver("<mongo url>");
MyCollection = new Mongo.Collection("collection_name", { _driver: myDatabasee });
});
}
The only you need to know its the name of the url <mongo url> it could be something like mongodb://127.0.0.1:27017/local or meteor
I am trying to connect to my Mongo database which is situated on the machine as my Meteor app. Here are two files in my app:
a.js:
if (Meteor.isServer) {
var database = new MongoInternals.RemoteCollectionDriver("mongodb://127.0.0.1:3001/meteor");
Boxes = new Mongo.Collection("boxes", { _driver: database });
Meteor.publish('boxes', function() {
return Boxes.find();
});
}
b.js:
if (Meteor.isClient) {
Meteor.subscribe('boxes');
Template.homeCanvasTpl.helpers({
boxes: function () {
return Boxes.find({});
}
});
}
But I keep getting a "Exception in template helper: ReferenceError: Boxes is not defined" error - any ideas?
How can you connect to a MongoDB with Meteor?
Scenario A: Use the built-in DB as default
This is much simpler than what you did. When you run meteor you actually start a DB with the Meteor server, where Meteor listens on port 3000 and the database on port 3001. The Meteor app is already connected to this database at port 3001 and uses a db named meteor. There is no need whatsoever to fall back to MongoInternals.RemoteCollectionDriver. Just remove that code and change things to:
Boxes = new Mongo.Collection("boxes"); // use default MongoDB connection
Scenario B: Use a different DB as default
Using the MONGO_URL environment variable you can set the connection string to a MongoDB when starting the Meteor server. Instead of the local port 3001 database or an unauthenticated connection you can specify exactly where and how to connect. Start your Meteor server like this:
$ MONGO_URL=mongodb://user:password#localhost:27017/meteor meteor
You can also leave out the user:password# part of the command if no authentication is needed.
Scenario C: Connect to a second (3rd, etc) DB from the same Meteor app
Now we need to use MongoInternals.RemoteCollectionDriver. If you wish to use another database that is not the default DB defined upon starting the Meteor server you should use your approach.
var database = new MongoInternals.RemoteCollectionDriver('mongodb://user:password#localhost:27017/meteor');
var numberOfDocs = database.open('boxes').find().count();
Bonus: Why should you not use MongoInternals with Mongo.Collection?
As the docs indicate you should not pass any Mongo connection to the new Mongo.Collection() command, but only a connection to another Meteor instance. That means, if you use DDP.connect to connect to a different server you can use your code - but you shouldn't mix the MongoInternals with Mongo.Collection - they don't work well together.
Based on feedback from saimeunt in the comments above, s/he pointed out that MongoInternals is unavailable to the client portion of a Meteor app. Therefore, the solution was to add in the line "Boxes = new Mongo.Collection("boxes");" to the client logic - here was the final working solution:
a.js:
if (Meteor.isServer) {
var database = new MongoInternals.RemoteCollectionDriver("mongodb://127.0.0.1:3001/meteor");
Boxes = new Mongo.Collection("boxes", { _driver: database });
Meteor.publish('boxes', function() {
return Boxes.find();
});
}
b.js
if (Meteor.isClient) {
Boxes = new Mongo.Collection("boxes");
Meteor.subscribe('boxes');
Template.homeCanvasTpl.helpers({
boxes: function () {
return Boxes.find({});
}
});
}
Meteor has 2 different environment : the server environment running on Node.JS and the client environment running in browsers.
In your code you declare the Boxes Mongo collection only in the server environment, you need to take this declaration out of the Meteor.isServer condition (and BTW don't use these, separate your code in server/, client/ and lib/ directories).
Also, not sure if you need to connect to your MongoDB this way, maybe you should look into the MONGO_URL environment variable it probably already does what you need ? (provide a mongo connection URL to a distant (or local) Mongo server).
I am using SailsJS 0.10.5.
I purchased a production MongoDB from Heroku and it created a variable with the new database url as follows:
mongodb://heroku:**password**#candidate.32.mongolayer.com:10485,candidate.13.mongolayer.com:10455/app123
However, when running the app in production environment only, the app fails to connect to database:
A hook (`session`) failed to load!
Could not load Connect session adapter :: connect-mongo
at new MongoStore (/app/node_modules/connect-mongo/lib/connect-mongo.js:115:19)
at validateDatabaseName (/app/node_modules/connect-mongo/node_modules/mongodb/lib
/mongodb/db.js:235:59)
at Hook.Session.initialize (/app/node_modules/sails/lib/hooks/session/index.js:20
5:37)
Error from adapter:
Error: database names cannot contain the character '.'
at new Db (/app/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/db.js
Note that when I copied the string locally and ran the app it worked perfectly.
I saw some workarounds suggest using Mongoose, but I want to stick to connect-mongo / sails-mongo
EDITED
I now managed to connect to the db by removing the replica set and simply add:
mongodb://heroku:**password**#candidate.32.mongolayer.com:10485/app123
However, a new error arrived:
Error: Error setting TTL index on collection : sessions
throw message;
at /app/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/cursor.js:700
at commandHandler (/app/node_modules/connect-mongo/node_modules/mongodb/lib/mongo
at Cursor.close (/app/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb
at /app/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/db.js:1882:9
at Server.Base._callHandler (/app/node_modules/connect-mongo/node_modules/mongodb
at /app/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection/se
It keeps crashing the app.
Ideas?
Try to setup and download mongo-uri to parse the url automatically