nodejs disconnect mongoose connection after operations - javascript

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

Related

Using Mongo/Mongoose, why is an entirely new database created when adding a document to an existing collection?

https://i.imgur.com/w5quRwA.jpg
I manually created a database called "shoppingitems" on the mongodb website console. I then created a model called "products" in an Express app and connected to the database. A collection called "products" was added to the "shoppingitems" database like I expected.
I then went to add a document to the "shoppingitems.products" collection, but instead an entirely new database called "test" was created, with a products collection and my submitted document in that 'test.products" collection instead of the "shoppingitems.products" collection like I intended.
Is there something wrong with my code? I make no mention of a "test" database anywhere, so IDK why it was created in the first place.
index.js
//Express
var express = require("express");
const app = express();
app.use(express.json());
//Mongoose
const dotenv = require("dotenv");
dotenv.config();
const mongoose = require("mongoose");
mongoose
.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("db connection succesfull"))
.catch((err) => console.log(err));
//CORS
const cors = require("cors");
app.use(cors());
//Routes
const productRoute = require("./routes/products");
app.use("/", productRoute);
//RUN INDEX.JS
app.listen(5000, () => {
console.log("backend server is running");
});
routes/products.js
var express = require("express");
var router = express.Router();
var Product = require("../models/Products");
/* GET PRODUCTS FOR HOMEPAGE */
router.get("/", async (req, res) => {
try {
productList = await Product.find();
res.json(productList);
} catch (error) {
console.log(error);
}
});
//POST PRODUCTS TO DATABASE
router.post("/", async (request, response) => {
console.log("request.body= ", request.body);
const newProduct = new Product(request.body);
try {
const savedProduct = await newProduct.save();
response.status(201).json(savedProduct);
} catch (err) {
response.status(500).json(err);
}
});
module.exports = router;
models/Products.js
const mongoose = require("mongoose");
const ProductSchema = new mongoose.Schema({
name: { type: String },
price: { type: Number },
description: { type: String },
image: { type: String },
stripeId: { type: String },
});
module.exports = mongoose.model("Product", ProductSchema);
Am I missing something? I don't see anything in the code that would be causing this and creating a "test" database. I've only used Mongo once or twice before though so I'm not exactly an expert. Can anybody here see what I'm doing wrong?
I'll post any additional code or information that you think is necessary to solving this. Just tell me what else you need to see.
test is the default database name used if you don't specify one. I also notice that nowhere in the code is a shoppingsitems database mentioned.
The connection string could contain the database name, but in this code that is taken from an environment variable.

Mongoose model queries hang in node

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 ;

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

View Mongo DB in Mongo compass

I'm new to MongoDB and Node. I have connected to Mongo using below
const mongoose = require("mongoose")
mongoose.connect('mongodb://localhost/testaroo', {
useNewUrlParser: true
})
mongoose.connection.once('open', function() {
console.log("Connection has been made ..")
}).on('error', function(error) {
console.log("Connection error", error)
});
And I created the below model
const mongoose = require('mongoose')
const schema = mongoose.Schema;
const marioCharSchema = new schema({
name: String, // Optional
weight: Number // Optional
})
const marioCharModel = mongoose.model('mariochar', marioCharSchema);
module.exports = marioCharModel;
EDIT
Inserting Data
const assert = require('assert');
const mariochar = require('../test/models/mariochar')
// Describe tests
describe('Saving records', function () {
//Create tests
it("Saving records to database", function (done) {
const char = new mariochar({
name = "Test",
weight: 45
});
char.save().then(
function () {
assert(char.isNew === false)
done();
}
)
})
})
And I tried to save a new record to this model and I tested it using mocha and it saved successfully. Now I want to view my database and my records using Mongo compass.
I tried to connect to mongodb://localhost/testaroo on port 27017
but I couldn't see my database. So what I'm missing here?
FIXED
For future viewers I fixed it by passing this option useUnifiedTopology: true to the to the MongoClient constructor
mongoose.connect('mongodb://localhost/Mydb', { useNewUrlParser: true, useUnifiedTopology: true })
Use mongo shell to insert and retrieve documents from the database, verify this works.
Use compass to view documents you inserted via the shell, verify this works.
Insert documents in your application and retrieve them via the shell, verify this works.
At this point whatever issue you have between your application and compass should be resolved.

Categories

Resources