Mongoose model queries hang in node - javascript

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 ;

Related

MongoDB client in Node

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})

How to separate the mongoose connect method to another JS file?

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');

Create in-memory database using mongodb-memory-server and mongoose

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;

nodejs disconnect mongoose connection after operations

I have the following mongoose script to connect to the local db and do some operations. But i have problem disconnecting it.
const mongoose = require('mongoose');
const db = mongoose.connect(`mongodb://localhost/mydb`);
const userModel = {
country: { type: String }
newField: { type: String }
};
const myUsersModel = mongoose.model('user',userModel);
myUsersModel.find({country:"USA"})
.then(users => users.forEach(function (doc) {
// some operations
doc.save();
db.disconnect();
}));
the problem is that the script doesn't disconnect the mongoose connection.
Could somebody help to fix this?
var db = mongoose.connect('mongodb://localhost:27017/somedb', { useMongoClient: true })
//do stuff
db.close()

Getting error in nodejs when querying mongodb data?

I am getting error in nodejs console (see screenshot for more clarification).
In matches.js :
const mongoose = require('mongoose');
let Schema = mongoose.Schema;
const matchSchema = new Schema({
match_id:{
type:Number; <---- line 8
required:true;
},
season:{
type:Number;
required:true;
}
.....
.....
});
const matches = mongoose.model('matches', matchSchema);
module.exports = matches;
// Get matches
module.exports.getmatches = (callback, limit) => {
matches.find(callback).limit(limit);
}
In app.js :
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
matches = require('./models/matches');
mongoose.connection.openUri('mongodb://localhost:27017/IPL');
const db = mongoose.connection;
app.get('/home', (req, res) => {
matches.getmatches((err, match) => {
if(err){
throw err;
}
res.json(matches);
});
});
app.listen('5000');
console.log('Running on port 5000....')
I have made model folder which contains matches.js I am trying to access data from mongodb and when to display it as JSON data on API endpoint i.e localhost://5000/home
This is a basic JavaScript Object declaration error. A JSON Object should look like this,
{
match_id: {
type: Number, //see the comma there?
required: true
}
}
Instead of using ,, you have used ; which will throw a syntax error. use this instead,
const matchSchema = new Schema({
match_id: {
type:Number,
required:true
},
season: {
type:Number,
required:true
}
.....
.....
});
Also, your getmatches function requires a limit passed as the second parameter, you need to pass that as well in the code.

Categories

Resources