I am trying to use multiple database connections in fastify with mongoose.
for single db code looks like
const mongoose = require('mongoose');
const fastifyPlugin = require('fastify-plugin')
mongoose.Promise = Promise; // Set mongoose to use ES6 Promises.
const reconnectTimeout = 5000; // ms.
const db = mongoose.connection;
async function dbConnector1(fastify, options) {
const conn1 = mongoose.connect("mongodb://localhost/db1", {
useNewUrlParser: true,
useUnifiedTopology: true,
retryWrites: false
})
.then(() => console.log( 'Connection to DB1 successful'))
.catch((err) => console.error(err));
};
module.exports = fastifyPlugin(dbConnector1,{
name: 'DB1'
})
I have put the above code in conn1.js
I have created a similar connection with different db in conn2.js and in index.js I am registering the db plugin as follows
await fastify.register(require('./src/db/conn1'))
await fastify.register(require('./src/db/conn2'))
I get the following error -
MongooseError: Can't call openUri() on an active connection with different connection strings. Make sure you aren't calling mongoose.connect() multiple times. See: https://mongoosejs.com/docs/connections.html#multiple_connections
Related
I am using Youtube tutorial about API using MongoDB and mongoose. However,I am keep getting this error whenever I do POST something on Postman.
"MongooseError: Operation products.insertOne() buffering timed out after 10000ms"
const { MongoClient } = require('mongodb');
const uri = "mongodb+srv://dusdn1102:" + process.env.MONGO_PW + "#node-rest-shop.wvxmj.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
client.close();
});
I am using visual studio code 1.57.1 and the version of MongoDB is 4.4.10.
Please can someone help me??
This will help you.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test')
.then(()=>console.log("DB Connected"))
.catch((err)=>console.log(err))
if you're using the mongoose model use this connection setting or as mentioned in mongoose website
You need to use mongoose to create a connection with the MongoDB. Add the following code to your app.js or server.js first.
const mongoose = require("mongoose");
const uri = "mongodb+srv://dusdn1102:" + process.env.MONGO_PW + "#node-rest-shop.wvxmj.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error: "));
db.once("open", function () {
console.log("Connected successfully");
});
Use this to open a connection and then proceed with the insert operation.
I have a node js server with a MongoDB. Can I do a 2 simultaneous connections to DB with different users?
Here is my connect code:
const mongoose = require("mongoose");
const { DB } = require("../constants");
const connectDB = async () => {
await mongoose.connect(DB, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
});
};
export const connect = connectDB;
I want make 2 connections, for example:
DB1 = mongodb+srv://USER:password#.mongodb.net
DB2 = mongodb+srv://USER1:password#.mongodb.net
Is it possible to do this in node js?
I can imagine yes since there are two instances, I think the most obvious response is you will never know until you try :D
I'm using mongoose. 5.8.2 and following a tutorial where the person is running mongoose on v3.5. I know there has been changes like useNewUrlParser has been deprecated and instead we use useUnifiedTopology but the problem is that whenever I use useUnifiedTopology then I get the error that it has been deprecated. Please have a look below and let me know what am I doing wrong
const mongoose = require('mongoose')
mongoose.createConnection('mongodb://127.0.0.1:27017/task-manager-api', {
useUnifiedToplogy: true,
useCreateIndex: true
});
const User = mongoose.model('User', {
name: {
type: String
},
age: {
type: Number
}
})
const me = new User({
name: 'Lallan',
age: '27'
})
me.save().then(() => {
console.log('Done')
}).catch((error) => {
console.log('error', error)
})
and the following is the error and I'm not able to connect mongoose with mongodb
the options [useUnifiedToplogy] is not supported
(node:6573) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(node:6573) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
What should I do to connect mongoose with mongodb?
The most default connection will be to just { useNewUrlParser: true }. You can use createConnection()(for multiple pools) as well as connect()(single pool).
From MDN a basic example will be:
//Import the mongoose module
var mongoose = require('mongoose');
//Set up default mongoose connection
var mongoDB = 'mongodb://127.0.0.1/my_database';
mongoose.connect(mongoDB, { useNewUrlParser: true });
//Get the default connection
var db = mongoose.connection;
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
Also,
If you need to create additional connections you can use
mongoose.createConnection(). This takes the same form of database URI
(with host, database, port, options etc.) as connect() and returns a
Connection object.
like,
const db = mongoose.createConnection('mongodb://user:pass#localhost:port/database', opts);
Maybe try giving it this way,
const mongoose = require('mongoose');
let db_uri = "'mongodb://localhost:27017/mydb"
mongoose.connect(db_uri, {
useNewUrlParser: true,
useUnifiedTopology : true
});
mongoose.set('useCreateIndex', true);
mongoose.set('useFindAndModify', false);
I am unable to connect to cloud mongodb with the following code. Can anyone please tell me whats wrong with this code?
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
//body parser middleware
app.use(bodyParser.json());
//db config
const db = require('./config/keys').mongoURI;
//Connect to mongo
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err));
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('server started on port ${port}'));
There are multiple steps you should follow to be able to connect Mongo DB so first make sure that you created an account plus connecting to a cluster, while creating it you'll be provided with enough info to create a cluster take your time and read.
after doing that the code is very simple:
const mongoose = require("mongoose");
mongoose.connect(
"mongodb+srv://[ACCOUNT NAME]:[PASSWORD]#cluster0-sxlgp.gcp.mongodb.net/test?retryWrites=true&w=majority", { useNewUrlParser: true }
);
replace ACCOUNTNAME and PASSWORD with info you provided when you created your MongoDB account
This can be found in their documentation try taking your time reading the documentation.
I believe your code looks good the error you are getting TransientTransactionError is temporary please use events to handle your connection result
mongoose
.connect(db, { useNewUrlParser: true })
mongooose.connection.once('open', () => {
console.log('db connection success');
});
mongooose.connection.on('err', (err) => {
console.log('db connection failed');
});
I'm new to MongoDB. Here is my setup
// backend/server.js
const dbRoute = mongodb://[username:password#]host1[:port1]/[database];
mongoose.connect(
dbRoute,
{ useNewUrlParser: true }
);
let db = mongoose.connection;
db.once("open", () => console.log("connected to the database"));
I am getting the console log message in the terminal. so I'm connected. I don't have the schema and this dbRoute is read only. How can get all the documents and save it to my local mongoDB ?