MongoRuntimeError: Connection pool closed - node.js

I am seeing my mongoose pool seemingly close before it inserts data as I am getting this error when making a call to my mongoose db in my cloud cluster
MongoRuntimeError: Connection pool closed
but I am awaiting all of the calls? so I'm unsure why I'm seeing this issue, maybe it has something to do with the way I am defining my client? hopefully someone has some tips or ideas on this
export const storeData = async (data) =>{
const uri = `mongodb+srv://plantmaster:${password}#cluster0.yey8l.mongodb.net/plantstore?retryWrites=true&w=majority`;
const client = await MongoClient.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverApi: ServerApiVersion.v1
});
const newPLantData = { name: "Company Inc", address: "Highway 37" };
await client.db("plantstore").collection("plantdata").insertOne(newPLantData, (err, res) =>{
if(err) throw err;
console.log(result)
})
await client.close();
};
I am calling this function on an express post route like so
// store data
app.post('/store', async function (req, res) {
await storeData(req.body);
res.send('data was stored')
})

i was facing the same error, but i fixed it by waiting 1500ms before closing the connection.
setTimeout(() => {client.close()}, 1500)

Try this example approach
import { MongoClient } from "mongodb";
const handler = async (req, res) => {
if (req.method === "POST") {
const { email } = req.body;
if (!email || !email.includes("#")) {
res.status(422).json({ message: "Entered email is not valid" });
return;
}
const url = <your-mongo-url>
const client = new MongoClient(url);
await client.connect();
const collection = client.db("events").collection("newsletter");
try {
await collection.insertOne({ email });
return res.status(201).json({
message: "You have successfully signed up to newsletters!",
email,
});
} catch (error) {
throw res.status(500).json({ message: "Server error occured" });
} finally {
client.close();
}
}
};
export default handler;

Related

Connecting MongoDB with NodeJS results in "collection is not a function" TypeError

I am new to MongoDB. I am trying to establish a connection between my ExpressJS server and a MongoDB database. This is my code:
const PRIMARY_SERVER = "mongodb://localhost:27017/";
const { MongoClient } = require("mongodb");
const client = new MongoClient(PRIMARY_SERVER, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
async function connect() {
try {
await client.connect();
console.log("Connected");
module.exports = client.db("mydb");
const app = require("../app.js");
app.listen(5050);
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
connect();
The connection gets established fine but as soon as this function gets called:
router.post("/pushbill", async function (req, res) {
databaseConnection.collection("bills").insertOne(object, function(err, result){
if(err) {
result.status(400).send("Error inserting matches.");
} else {
console.log(`Added a new match with id 0`);
result.status(204).send();
}
});
});
I get this error: "(node:17984) UnhandledPromiseRejectionWarning: TypeError: databaseConnection.collection is not a function".
I've searched for this issue for a few hours now but can't seem to find a solution. I tried several different methods of connecting my database, one of them included this ticket: db.collection is not a function when using MongoClient v3.0 . I am using MongoDB 4.13.0.
It was an issue where the connection to MongoDB kept closing before any operation was made.
I solved this issue by opening connection each time a request gets made, and waiting till the operations are done with a callback or in this case a timeout.
const connDB = async(operations, response) => {
try{
const client = new MongoClient('mongodb ip here', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
await client.connect().then(function(result){
}).catch(function(err){
throw err;
});
const db = await client.db('my_db');
operations(db);
setTimeout(() => {client.close()}, 1500)
} catch(err){
console.error(err);
response.status(500).send({ message: 'Error connecting or operating the database', error: err});
await client.close();
}
}

MongoDB insertMany() working fine and data is saving to the Database, but gives 400 Bad request error

This is my node JS
const router = require("express").Router();
const Posts = require("../../models/vendorProjectsDatabaseExcellUpload");
router.post('/vendorProjectsDatabasesExcell/save',(req,res) => {
const newPost = req.body;
// console.log(newPost);
// Posts.insertMany(newPost).then((err) =>{
// if(err){
// return res.status(400).json({
// error:err
// });
// }
// return res.status(200).json({
// success:"Project Details Added Successfully"
// });
// });
try {
const options = { ordered: true };
const result = Posts.insertMany(newPost, options).then((err) =>{
if(err){
return res.status(400).json({
error:err
});
}
return res.status(200).json({
success:"Project Details Added Successfully"
});
});
console.log(`All documents were inserted`);
} finally {
console.log('done');
}
});
module.exports = router;
This is my React.js
const uplaodHandler = async (e) => {
// const uplaodHandler = (e) => {
e.preventDefault();
const newPost = items;
// console.log(newPost);
await axios
.post('http://localhost:8072/vendorProjectsDatabasesExcell/save', newPost)
.then((result) => {
alert(result);
alert('New Project Added now');
// navigate('/dashboard/DatabasesUploadProjectFilesVendorProjects', { replace: true });
console.log(newPost);
})
.catch((error) => {
console.log(error);
// console.log(error.response.data);
// console.log(error.response.status);
// console.log(error.response.headers);
});
};
Other post and put request in other pages of the same app is works fine without any error.
In here also the json data array post to the mongo DB without any issue. Only problem is it is giving the bad request 400 error.
Just modify this part:
const result = Posts.insertMany(newPost, options)
.then((res) =>{
return json({success:"Project Details Added Successfully"});
}).catch((err) => {
return json({error:err});
});

How to delete a doc with id with mongoose?

I want to delete a doc with id in mongoose. It executes the method but doesn't delete that doc in MongoDB Altas.
Note:Everthing is correct and also Passing id correctly in PostMan.
here is my controller :
const Post = require("../models/Post");
const mongoose = require("mongoose");
exports.postPost = async (req, res) => {
try {
const post = await new Post({
_id: new mongoose.Types.ObjectId(),
title: req.body.title,
desc: req.body.desc,
}).save();
console.log("Saved in db!");
return res.status(201).json({
success: true,
data: post,
});
} catch (error) {
return res.status(500).json({
success: false,
message: "Server Error",
});
}
};
exports.deletePost = async (req, res) => {
let postID = req.params.id;
await Post.deleteOne({ _id: postID }, (err, data) => {
if (err) {
res.status(500).json({
message: "Something went wrong, please try again later.",
});
} else {
res.status(200).json({
message: "Post Deleted",
data: data,
});
}
});
};
here is my posts route:
const express = require("express");
const router = express.Router();
const {
postPost,
deletePost,
} = require("../controllers/posts_controller");
router.route("/:id").delete(deletePost);
router.route("/").post(postPost);
module.exports = router;
here is my postman :
here is my mongodb altas:
use the findOneAndDelete({_id:postId}) instead of deleteOne in posts controller
Or
use findByIdAndDelete(postId) instead of deleteOne in posts controller
exports.deletePost = async (req, res) => {
let postID = req.params.id;
await Post.findByIdAndDelete(postID, (err, data) => {
if (err) {
res.status(500).json({
message: "Something went wrong, please try again later.",
});
} else {
res.status(200).json({
message: "Post Deleted",
data: data,
});
}
});
};

Issue with update in Mongoose

I have wrote a simple Update function. Its working fine for some minutes and then again its not working. Where I am going wrong? Please help me. I use PUT as my method.
code
accept = (req, res) => {
this._model.update({
user: new mongoose.Types.ObjectId(req.params.uid)
}, {
$set: {
status: 'active'
}
}, (err, obj) => {
if (err || !obj) {
res.send(err);
} else {
res.send(obj);
}
});
}
Model
{
"_id":"5d3189a00789e24a23438a0d",
"status":"pending",
"user":ObjectId("5d3189a00789e24a23438a0d"),
"code":"CT-123-345-234-233-423344",
"created_Date":"2019-07-19T09:13:04.297Z",
"updated_Date":"2019-07-19T09:13:04.297Z",
"__v":0
}
Request
api.abc.com/api/accept/5d3189a00789e24a23438a0d
Sometime it is returing values and sometime null.
You can use the following code to ensure the model is tied to a connection. This could be an issue of connection to the database.
const config = require('./config');
console.log('config.database.url', config.database.url);
return mongoose.createConnection(config.database.url, {
useMongoClient: true
})
.then((connection) => {
// associate model with connection
User = connection.model('User', UserSchema);
const user = new User({
email: 'someuser#somedomain.com',
password: 'xxxxx'
});
const prom = user.update();
// Displays: 'promise: Promise { <pending> }'
console.log('promise:', prom);
return prom
.then((result) => {
// Don't see this output
console.log('result:', result);
})
.catch((error) => {
// Don't see this output either
console.log('error:', error);
});
})
.catch((error) => {
console.log(error);
});
I think you need to use promise or async/await, try this
accept = async (req, res) => {
try {
const result = await this._model.update({
user: new mongoose.Types.ObjectId(req.params.uid)
}, {
$set: {
status: 'active'
}
});
return res.send(result);
} catch (e) {
return res.send(e);
}
};

ExpressJS - populate before save asyc await

I want to populate user in Feed model, and i cant do that, this is what i tried
router.post('/', async (req, res) => {
const newFeed = new Feed(req.body);
try {
const article = await newFeed.populate('created_by');
const finalArticle = await newFeed.save();
res.status(200).json({
success: true,
message: "Successfully created.",
data: finalArticle
})
} catch (err) {
next(err)
}
});

Resources