I have initialized the connection to my mongodb and now export the db to other nodejs files. How can I do that?
i thought of something like this but it is giving errors.
let database;
export const connectDB = async () => {
const client = new MongoClient(config.dbUri, {
useUnifiedTopology: true,
});
try {
await client.connect();
database = client.db('azkaben');
logger.info('Connected to Database');
} catch (e) {
logger.error(e);
} finally {
await client.close();
}
};
export default database
Error : undefined value of database
database will always be null when you import it.
connectDB is aync call by the time it executes your database variable is already loaded as null.
connectDB you can return database from here.
export const connectDB = async () => {
const client = new MongoClient(config.dbUri, {
useUnifiedTopology: true,
});
try {
await client.connect();
database = client.db('azkaben');
return database; // you can get from here
logger.info('Connected to Database');
} catch (e) {
logger.error(e);
} finally {
await client.close();
}
};
Updated code
export const connectDB = async () => {
if (database) return database; // return if database already connected.
const client = new MongoClient(config.dbUri, {
useUnifiedTopology: true,
});
try {
await client.connect();
database = client.db('azkaben');
return database; // you can get from here
logger.info('Connected to Database');
} catch (e) {
logger.error(e);
} finally {
await client.close();
}
};
Related
I am trying to delete a collection from mongodb using postmap API. Below is my code.The update function is working fine.But, delete function isn't working. It's displaying internal server error.I dont know why?
const router = require("express").Router();
const User = require("../models/User");
const bcrypt = require("bcrypt");
//uodate
router.put("/:id", async (req, res) => {
if ((req.body.userId === req.params.id) || req.body.isAdmin) {
if (req.body.password) {
try {
const salt = await bcrypt.genSalt(10);
req.body.password = await bcrypt.hash(req.body.password, salt);
}
catch (err) {
return res.status(500).json(err);
}
}
try {
const user = await User.findByIdAndUpdate(req.params.id, {
$set: req.body,
});
return res.status(200).json("Account has been updated");
}
catch (err) {
return res.status(500).json(err);
}
}
else return req.status(400).json("You can only update your account!!!");
});
//delete
router.delete("/:id", async (req, res) => {
if ((req.body.userId === req.params.id) || req.body.isAdmin) {
try {
await User.deleteOne(req.params.id);
return res.status(200).json("Account has been deleted");
}
catch (err) {
return res.status(500).json(err);
}
}
else return res.status(400).json("You can only update your account!!!");
});
module.exports = router;
Help me with thispostman API screenshot.
Try this:
await User.deleteOne({_id:req.params.id});
You are using deleteOne() method. If you want to delete whole collection, you should use deleteMany() method:
await User.deleteMany({});
The Model.deleteOne method expects a filter object, like {name: "value'"}. You are passing req.params.id which is a string. If you dig out the full text of the error, it will likely complain about that string not being an object.
You probably meant to use the Model.findByIdAndDelete method like
await User.findByIdAndDelete(req.params.id);
I'm trying to call my global variables in my controller but i got an error variable is not defined. Please see the code below for your reference. Hoping to solve my problem. Thank you Guys
**server.js **
const serverConfig = require('./config/server.config')
const app = require('fastify')({ logger: true })
require('./models/response.model')
const mongoose = require('mongoose')
const conn = require('./config/monggo.config')
require('./routes/dbm.routes')(app)
const connect = async () => {
try {
await mongoose.connect(conn.uri)
console.log('Connected to Mongoose!')
} catch (error) {
console.log(error)
}
}
connect();
app.listen(serverConfig.port, '::', (err, address) => {
if (err) {
app.log.error(err)
process.exit(1)
}
console.log('Listening at', address)
})
response.model.js
module.exports = function () {
global.successModel = {
status: 'sucess',
statusCode: 0,
isSuccess: true,
message: ''
}
global.failModel = {
status: 'failed',
statusCode: 1,
isSuccess: false,
message: 'Error encountered while processing request.'
}
}
**monggo.controller.js
**
exports.getProducts = async (req, res) => {
//find Products in the databse
Product.find({}, (err, product) => {
//send error message if not found
if (err) {
res.send(err);
}
//else pass the Products
res.send(successModel);
})
await res;
}
Hoping to solve my problem. Thank you
The './models/response.model' file exports a function that you need to call to "install" your globals.
- require('./models/response.model')
+ require('./models/response.model')()
As a suggestion, you should avoid to use globals, in fastify you can use:
decorator to add to your app instance useful data such as configs
Moreover, your mongoose connection is unrelated with Fastify, you can encapsulate it into a plugin to be sure that fastify is starting after connecting to the database:
const fp = require('fastify-plugin')
app.register(fp(async function connect (instance, opts) {
await mongoose.connect(conn.uri)
}))
My mongoose model works fine with promises .then() and .catch. However, if I do await User.findOne({ email }), my response test in Postman infinitely awaits.
class UserController
{
...
static async RegisterUser(req, res)
{
...
const doesUserExist = await User.findOne({ email });
if(!doesUserExist)
{
return res.status(400).json({ message: 'User does not exist' });
}
...
}
}
Here is my DB connection if necessary:
const connectDB = async () => {
try {
console.log('Connecting to database...');
const admin = process.env.API_USN;
const adminPassword = process.env.API_PASS;
const options = {
useNewUrlParser: true,
useUnifiedTopology: true
};
const databaseURL = process.env.APP_DB_URL
.replace('<password>', adminPassword)
.replace('<admin>', admin)
.replace('<username>', admin)
console.log(`Connecting to: ${databaseURL}`)
const conn = await mongoose.connect(databaseURL, options);
console.log(`MongoDB Connected: ${conn.connection.host}`);
} catch (error) {
console.log(error);
process.exit(1);
}
};
Anyone know why async/await infinitely waits but .then()/.catch() works perfectly fine? I even tried awaiting User.findOne().exec()
So I'm trying to fetch every document which matches the same ID.
Here is what did I do:
app.get('/comments/:id', async (req,res)=>{
let db = await connect();
let id = req.params.id;
console.log(id);
let results = await db.collection('comments').find({postID: id});
console.log(results);
res.json(results);
});
How to send more than one documents with the same ID?
I want to select every postID property with the same ID
My code while connecting with MongoDB:
const { MongoClient } = require('mongodb');
let connection_string = 'mongodb+srv://user:pass#host/myFirstDatabase?retryWrites=true&w=majority';
let client = new MongoClient(connection_string, {
useNewUrlParser: true,
useUnifiedTopology: true
});
let db = null
export default () => {
return new Promise((resolve, reject) =>{
if (db /*&& client.isConnected()*/){
resolve(db)
}
client.connect(err => {
if(err){
reject("Error while connecting: " + err)
}
else{
console.log("Successful connection!")
db = client.db("posts")
resolve(db)
}
});
})
};
Make sure you are importing client from the file where you are making the connection.
app.get("/comments/:id", async (req, res) => {
await client.connect(); // Simply connect() won' work.
const db = client.db("posts"); // Specify the db here
let id = req.params.id;
console.log(id);
let results = await db.collection("comments").find({ postID: id }).toArray(); // Without toArray(), it returns a cursor to the array.
console.log(results);
res.json(results);
});
db.js
const { MongoClient } = require("mongodb");
let connection_string = "mongodb+srv://admin:admin#cluster0.3ctoa.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
let client = new MongoClient(connection_string, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = function () {
return new Promise((resolve, reject) => {
client.connect((err) => {
if (err) {
reject("Došlo je do greške prilikom spajanja: " + err);
} else {
resolve("Successful connection!");
}
});
});
};
module.exports = { client, db };
And instead of importing connect, import both client and db from db.js.
If you are talking about the id created by mongoose.scheme.Types.objectId, There is only one entry with that ID
I've been reading about async and await in JS and tried to implement them in my code (which I totally messed up).
Here is my JS.
var express = require('express');
var router = express.Router();
var jsforce = require('jsforce');
const SEC_TOKEN = 'SEC_TOKEN';
const USER_ID = 'USER_ID';
const PASSWORD = 'PWD';
const { default: axios } = require('axios');
router.get("/", async (req, res, next) => {
await initConnect;
await soqlData;
await slackPostTest;
});
initConnect = async () => {
var conn = new jsforce.Connection({
loginUrl: 'https://login.salesforce.com'
});
await conn.login(USER_ID, PASSWORD + SEC_TOKEN, (err, userInfo) => {
if (err)
console.log(err);
else {
console.log(userInfo.Id);
}
});
}
soqlData = async () => {
await conn.query('Select Id, Name from Account LIMIT 1', (err, data) => {
if (err)
console.log(err);
else
return data.records[0];
})
}
slackPostTest = async () => {
await axios.post('SLACK_WEBHOOK', {
"text": "soqlRes"
})
}
module.exports = router;
What I am trying to achieve?
Initialize my connection by passing in SEC_TOKEN, USER_ID, PASSWORD to my initConnect function this will give me a connection (conn).
Use this conn and query my salesforce instance and get some other data.
post some message(currently irrelevant, but will hook up with the above response later) to my slack endpoint.
Also can someone please give me a little detailed explanation of the solution (in terms of async/await)?
Thanks
Assuming everything else about your JsForce API usage was correct (I have no experience with it, so I can't say), here's how to promisify those callback-based APIs and call them.
var express = require("express");
var router = express.Router();
var jsforce = require("jsforce");
const SEC_TOKEN = "SEC_TOKEN";
const USER_ID = "USER_ID";
const PASSWORD = "PWD";
const { default: axios } = require("axios");
router.get("/", async (req, res, next) => {
const { conn, userInfo } = await initConnect();
const data = await soqlData(
conn,
"Select Id, Name from Account LIMIT 1",
);
await slackPostTest(data.records[0]);
});
function initConnect() {
const conn = new jsforce.Connection({
loginUrl: "https://login.salesforce.com",
});
return new Promise((resolve, reject) => {
conn.login(USER_ID, PASSWORD + SEC_TOKEN, (err, userInfo) => {
if (err) return reject(err);
resolve({ conn, userInfo });
});
});
}
function soqlData(conn, query) {
return new Promise((resolve, reject) => {
conn.query(query, (err, data) => {
if (err) return reject(err);
resolve(data);
});
});
}
function slackPostTest(soqlRes) {
return axios.post("SLACK_WEBHOOK", {
text: soqlRes,
});
}
module.exports = router;