For my discord bot, I was thinking of separating the mongoose connect method and other initialization to a separate JS file. I was able to move everything except for the connect method. I don't know how this could be done.
Try below code
// Declare mongoose as global
global.mongoose = require('mongoose');
// In Separate file
const url = "Your URL";
//BUILD A CONNECTION
mongoose.connect(url).then(() => { console.log('Connected To database :)')})
.catch( err => console.log('error', err));
module.exports.mongoose = mongoose
// Schema File
const users = new mongoose.Schema({
name : String,
}, {
timestamps : true
})
module.exports = mongoose.model('users', users);
// In model Path
const usersModel = require('Schemas/users')
now you can use usersModel to query documents/table
// suppose this filename is, mongoose.db.config.js
const mongoose = require("mongoose");
function mongooseConnectDB(uri) {
mongoose
.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
})
.then((result) =>
console.log("Mongoose connected to ", result.connections[0].host)
)
.catch((err) => console.log("error connecting to the database", err));
}
module.exports = mongooseConnectDB;
Now in your app(main.js/index.js/server.js), you can do simply like this
const mongooseConnectDB = require("./mongoose.db.config");
mongooseConnectDB('url_of_your_db');
Related
I've been trying to connect my application to my database, but it has not been possible. I've tried this below, and it still did not recognize my models
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = process.env.MONGODB_URL;
// Database Name
const dbName = 'KaydeeAcedemy';
// Use connect method to connect to the server
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
I've also tried using this connection string, yet no headway.
const { MongoClient } = require('mongodb');
const uri = process.env.MONGODB_URL;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
when I try to add a new user from my application, i get this error as a result of the database.
Operation `users.findOne()` buffering timed out after 10000ms
the mongodb url looks like this:
MONGODB_URL = mongodb+srv://Kaydeeacademy:**************#cluster0.ehclf.mongodb.net/KaydeeAcademy?retryWrites=true&w=majority
I don't know if I missed something in the connection string or somewhere.
Can you test/compare out some of my code (working)
// have you called in the dot.env file?
require('dotenv').config()
const express = require('express')
const mongoose = require('mongoose')
// don't include the "useNewUrlParser: true, useUnifiedTopology: true" see answer below:
// https://stackoverflow.com/questions/68915722/option-usefindandmodify-is-not-supported
// make sure there are no spaces in the dot.env file
mongoose.connect(process.env.MONGO_URI)
.then(() => console.log("db connected!"))
.catch(err => console.error("db connection failed ", err))
I have a database file where I set up my schemas/models for mongo and export them. Whenever I reference the models for queries in other files, then run the file in node, it hangs. I get my data back but I have to manually close node. I have tried other solutions like mongoose.disconnect() at the end of my database file but that breaks my query.
database.js
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true, useUnifiedTopology: true })
const exampleSchema = new mongoose.Schema({
name: String,
stuff: {}
})
const Example = mongoose.model('Example', exampleSchema)
module.exports = {
Example
}
function.js
const { Example } = require('../database')
const doSomething = async (name) => {
const data = await Example.find({ name: name })
}
doSomething('jwhunt19')
use this url mongodb://localhost:27017/test for database connection
mongoose.connect('mongodb://localhost:27017/test',
{ useNewUrlParser: true, useUnifiedTopology: true })
27017 is your port number for databse coonection, if you want ,you can change it to another number
jsut try like this:
const mongoose = require('mongoose');
const connection = mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true, useUnifiedTopology: true })
const exampleSchema = new mongoose.Schema({
name: String,
stuff: {}
})
const doSomething = async (name) => {
const data = await Example.find({ name: name })
}
doSomething('jwhunt19')
const Example = connection.model('User', exampleSchema);
module.exports = connection;
function.js
const connection = require("./database");
const Example = connection.models.Example ;
Im trying to connect mongodb in node.js and take the link to client to the outer variable.
I need to create a module that would return a result of .find() method. How can i do this?
const MongoClient = require('mongodb').MongoClient
let client
mongoClient = new MongoClient('mongodb://localhost:27017/', {useUnifiedTopology: true, useNewUrlParser: true})
mongoClient.connect((err, db) => {
if (err) {
return console.log(err)
}
client = db
})
const database = client.db('db')
const collection = database.collection('collection')
client.close()
And the error
const database = client.db('db')
^
TypeError: Cannot read property 'db' of undefined
As the comment suggests, you can use async/await to wait for the connection to be established, and do the error handling with a try/catch statement:
try {
const client = await mongoClient.connect()
const database = client.db('db')
const collection = database.collection('collection')
} catch(e) {
console.log(e)
}
Don't forget to use it in an async function.
Update
An async function example, you may want to return the collection:
const getData = async () => {
try {
mongoClient = new MongoClient('mongodb://localhost:27017/', {useUnifiedTopology: true, useNewUrlParser: true})
const client = await mongoClient.connect()
const database = client.db('db')
const collection = database.collection('collection')
client.close()
return collection
} catch(e) {
console.log(e)
}
}
after uri you must define db name
mongoClient = new MongoClient('mongodb://localhost:27017/', {useUnifiedTopology: true, useNewUrlParser: true})
like this
mongoClient = new MongoClient('mongodb://localhost:27017/shop', {useUnifiedTopology: true, useNewUrlParser: true})
I want to create a in-memory database using mongodb-memory-server and mongoose. Can anyone show the correct way to do it.
From version 7 and above
// this no longer works
const mongo = new MongoMemoryServer();
const uri = await mongo.getUri(); // ERROR: instance not started
// it is now
const mongo = await MongoMemoryServer.create();
const uri = mongo.getUri();
https://nodkz.github.io/mongodb-memory-server/docs/guides/migration/migrate7/#no-function-other-than-start-create-ensureinstance-will-be-starting-anything
Read the documentation here and came accross the following solution.
const mongoose = require('mongoose');
const { MongoMemoryServer } = require('mongodb-memory-server');
const mongoServer = new MongoMemoryServer();
mongoose.Promise = Promise;
mongoServer.getUri().then((mongoUri) => {
const mongooseOpts = {
useNewUrlParser: true,
useFindAndModify: false,
useCreateIndex: true,
useUnifiedTopology: true,
};
mongoose.connect(mongoUri, mongooseOpts);
mongoose.connection.on('error', (e) => {
console.log(e);
});
mongoose.connection.once('open', () => {
console.log(`MongoDB successfully connected to ${mongoUri}`);
});
});
module.exports=mongoose.connection;
This question already has answers here:
db.collection is not a function when using MongoClient v3.0
(13 answers)
Closed 3 years ago.
I'm setting up a new app using an Atlas Database with node and all i get is an error saying " MongoError: MongoClient must be connected before calling MongoClient.prototype.db".
const uri = "mongodb+srv://alberto:pass#lel-kicis.mongodb.net/test";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("students")
.then(db => console.log('DB conectada'))
.catch(err => console.log(error));
});
If you look at the mongodb connector docs, the syntax for MongoClient is new MongoClient(url, options, callback). The signature for the callback is (err, client) => { //body }.
If you don't pass in the optional callback, you get and instance of MongoClient (which is the case here). The connect method also expects the same callback signature, so your connection should be like:
const instance = new MongoClient(uri, { useNewUrlParser: true });
// notice 'client' in the callback
instance.connect((err, client) => {
if (err) console.log('failed to connect')
else {
console.log('connected')
const collection = client.db("test").collection("students")
...
}
});
mongodb connector also support promise, so you can also do:
// connection is a promise
const connection = instance.connect()
connection.then((err, client) => { // etc })
Using mongoose and mongodb-uri :
Here is the way I initialise the connection :
const mongoose = require('mongoose')
const uriUtil = require('mongodb-uri')
// Create a new connection
mongoose.Promise = global.Promise
// mongoose.set('debug', DEBUG)
const dbURI = uriUtil.formatMongoose(process.env.MONGO_URI)
const options = {
autoIndex: DEBUG,
autoReconnect: true,
useNewUrlParser: true
}
const conn = mongoose.createConnection(dbURI, options)
conn.on('open', () => console.log('DB connection open'))
conn.on('error', err => console.log(`DB connection error : ${err.message}`, err))
conn.on('close', () => console.log('DB connection closed'))
module.exports = conn
Using the connection string provided by mongoDb for driver node.js version 3.0 or later.
You are missing to initiate the mongo client.
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://alberto:pass#lel-kicis.mongodb.net/test";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("students")
.then(db => console.log('DB conectada'))
.catch(err => console.log(error));
});
Also, Atlas generate the initial connection code block for you. Follow the below steps.
Clck on connect button
Select Connect Your Application from the next window
On the next window, Select NodeJs as driver and select the required version. Also, select Full driver example for full code block
Now copy the code and use it directly.