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 ?
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.
my project have 1 react component that contain sub-component. Each component may have 1 mongodb database.i been wondering how to have multiple db?
my code so far can only connect to 1 db
in db i have connection.js as:
require("dotenv").config();
let mongoose = require("mongoose");
let mongoDB = process.env.DB_CONNECTION;
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true });
let connection = mongoose.connection;
connection.on(
"error",
console.error.bind(console, "MongoDB connection error:")
);
module.exports = connection;
in app.js i have:
const connection = require("./db/connection");
connection.once("open", () => {
console.log("connected to db");
const server = app.listen(process.env.PORT1 || 8081, () => {
console.log("listening on " + `${process.env.PORT1 || 8081}`);
});
});
How can i have another db (eg: /db/secondDatabase.js that same as the first db) and add it to app.js? many thanks in advance, i appreciate your help!!!
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
I am reading node.js mongodb driver tutorial
On the sample code below from the tutorial, it closes the client just after it finishes to do whatever it wants to do.
In case of web-server that constantly interacts with mongo, Is it really expected to reconnect to MongoDB and then close the connection with this procedure each time a request is coming? suggestions for better implementations are welcomed :)
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017,localhost:27018/?replicaSet=foo';
// Database Name
const dbName = 'myproject';
// Create a new MongoClient
const client = new MongoClient(url);
// Use connect method to connect to the Server
client.connect(function(err) {
assert.equal(null, err);
console.log("Connected correctly to server");
const db = client.db(dbName);
client.close();
});
You can use this, it uses a connection pool there is no need to close the connection.
var mongoose = require("mongoose");
var db = 'mongodb://localhost/dataBaseName';
mongoose.connect(db, {
useNewUrlParser: true
});
var db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
fs.readdirSync(__dirname + "/models").forEach(function (filename) {
if (~filename.indexOf(".js")) require(__dirname + "/models/" + filename);
});
mongoose.set("useFindAndModify", false);
mongoose.set("useCreateIndex", true);
Not necessary to close and open connection multiple times in same runtime. Connect once when app starts.
I'm testing mongoDB connection in node.js with mongoose. I follow the official guide of mongoose and when I try to connect like they said, mongoose always says I'm connected even if the URI given is fake or wrong. Is my connection trying correct ?
I want to connect my app to a database called 'technicaltest'.
My code:
const mongoose = require('mongoose');
const db = mongoose.createConnection('mongodb://localhost/technicaltest', {useNewUrlParser: true});
db.on('connected', () => {
console.log('Connected to mongoDB !');
});
db.on('disconnected', () => {
console.log('Disconnected to mongoDB !');
});
The console ouput:
> set PORT=3001 && node bin/www
Connected to mongoDB !
Same output for this code:
const mongoose = require('mongoose');
const db = mongoose.createConnection('mongodb://localhost/someWeirdyThingsHere', {useNewUrlParser: true});
db.on('connected', () => {
console.log('Connected to mongoDB !');
});
db.on('disconnected', () => {
console.log('Disconnected to mongoDB !');
});
I think if mongoose cannot connect to the right database in mongoDB nothing will be prompted in the console...
But here...
The 'connected' event is call anyway.
I think you forgot to add the port(27017) to your mongodb connection.
It should be
const db = mongoose.createConnection('mongodb://localhost:27017/technicaltest', {useNewUrlParser: true});