Connect mongodb v5 to nodejs - node.js

How to connect new mongodb v5 to nodejs
const express = require('express');
const app = express();
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
async function main() {
await client.connect();
}
const collection = client.db('internfeb').collection('dashboard');
const port = process.env.PORT || 7710;
app.get('/health',async(req,res) => {
const output = []
const cursor = collection.find({});
for await (const doc of cursor) {
output.push(doc)
}
cursor.closed;
res.send(output)
})
app.post('/addUser',async(req,res) => {
await collection.insertOne(req.body)
res.send('Data Added')
})
app.listen(port,() => {
main()
console.log(`Running on thr port ${port}`)
})

You should initialize collection after the client has connected:
const express = require('express');
const app = express();
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
let collection;
async function main() {
try {
await client.connect();
collection = client.db('internfeb').collection('dashboard');
} catch (err) {
console.log(err);
process.exit(1);
}
}
const port = process.env.PORT || 7710;
app.get('/health', async (req, res) => {
const output = [];
const cursor = collection.find({});
for await (const doc of cursor) {
output.push(doc);
}
cursor.closed;
res.send(output);
});
app.post('/addUser', async (req, res) => {
await collection.insertOne(req.body);
res.send('Data Added');
});
app.listen(port, () => {
main();
console.log(`Running on thr port ${port}`);
});

Related

Mongo Save function callback not triggering

Mongo save callback is not triggering, but the document is getting saved in the db, Heres my code:
MongoDb Version : 6.0.1
Mongoose Version : 6.8.2
The call back not returning anything, but the documents are getting saved without any issues, why the call back is not triggering?
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const url = 'mongodb://127.0.0.1:27017/musicapp';
const cors = require('cors');
var jquery = require('jquery');
//Mongodb
mongoose.connect(url, { useNewUrlParser: true });
mongoose.set('strictQuery', true);
var conn = mongoose.connection;
conn.on('connected', function () {
console.log("Database Connected");
})
var artistSchema = new mongoose.Schema({
artistName: String,
artistDob: String,
artistBio: String
})
const artists = mongoose.model("artist", artistSchema);
function addArtist(aName, aDOB, aBIO) {
const newArtist = new artists({
artistName: aName,
artistDob: aDOB,
artistBio: aBIO
})
newArtist.save((err, data, numAffected) => {
if (!err) {
return true;
}
else {
return false;
}
});
}
//MongoDb
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html")
})
app.post("/addsongs", cors(), (req, res) => {
console.log("Add songs");
})
app.post("/addartist", cors(), (req, res) => {
var artistName = req.body.modalartistname;
var artistDOB = req.body.modalartistdob;
var artistBio = req.body.modalartistbio;
var addedArtist = addArtist(artistName, artistDOB, artistBio);
if (addedArtist) {
res.sendStatus(200);
}
else {
console.log("Failure")
res.sendStatus(400);
}
//console.log("Artist Added Sucessfully");
})
app.listen(3000, function () {
console.log("The Server is up and running");
})

export a function inside socket connection

I have created a socket server as shown below.
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server, {cors:{origin:'*'}})
const mongoose= require("mongoose")
const port = process.env.PORT || 4002;
server.listen(port, ()=>{
console.log(`Listening on port ${port}......`)
})
onlineUsers = [];
const addNewUser = (userId, socketId)=>{
!onlineUsers.some((user)=>user.userId === userId) &&
onlineUsers.push({userId,socketId})
}
const removeUser= (socketId) =>{
onlineUsers = onlineUsers.filter((user)=> user.socketId!==socketId)
}
const getUser = (userId)=>{
return onlineUsers.find(user=>user.userId ===userId)
}
io.on("connection", (socket=> {
console.log("User connected:", socket.id);
socket.on("disconnect",()=>{
removeUser(socket.id)
})
socket.on("newUser",(userId)=>{
addNewUser(userId, socket.id)
})
export function handleMessaging (userId,clientID,messageId )
{
const receiver = getUser(userId);
if(receiver)
{
io.to(receiver.socketId).emit("sendMessage", {data:"working properly"});
return true;
}
else return false
}
}));
I want to export the function handle messaging so that I can use it inside the API like (shown below) to see if a user is online and if yes, send a message.
But as someone new to programming, I can't figure out how to export handle messaging the proper way. I tried to use export but its telling me "Modifiers cannot appear here".
router.post('/:companyId' async (req, res) => {
const {userId,clientId,messageId} = req.body
handleMessaging (userId,clientID,messageId )
{
//do xyz
}
}

how to use async and await to connect to mongoDB database?

I am new to JavaScript and currently learning mongoDB with node.
The code Bellow is in callback functions but i want to connect to mongoDB database using async and await with try and catch .
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/selfdb");
mongoose.connection
.once("open", () => {
console.log("connection has been made!");
})
.on("error", (error) => {
console.log("connection error:", error);
});
I tried doing this way:
const mongoose = require("mongoose");
async function main() {
const uri = "mongodb://localhost/selfdb";
const client = new mongoose(uri);
try {
await client.connect();
console.log("connection has been made!");
} catch (e) {
client.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
but i got following error:
TypeError: mongoose is not a constructor
how could i do it the right way?
am i doing any silly mistake?
I believe the better way to connect is like this
const mongoose = require('mongoose')
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI)
console.log(`MongoDB Connected: ${conn.connection.host}`)
}
catch (error) {
console.log(error)
process.exit(1)
}
}
module.exports = connectDB
Mongo URI is in .env file, but you can replace it with your connection string (but more secure in .env file)
Then in server.js or index.js (entry file)
const connectDB = require('path_to_file')
connectDB()
I Tried this approach !! May be it could be helpful.
DBconn.js (MONGO_URL is from .env file & dev_db_url is optional here)
require('dotenv').config({ path: 'env/.env' });
const dev_db_url = 'local dev. db url is not defined.';
const mongoDB_URL = process.env.MONGO_URL || dev_db_url;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
const connectDB = async (cb) => {
try {
await mongoose.connect(mongoDB_URL, dbOptions)
.then(() => {
cb();
console.log("Connected to Database");
})
} catch (error) {
console.error("Could not Connect to Database", error)
}
};
module.exports = connectDB;
Server.js (Server will start to listen only after successful DB Connect)
require('dotenv').config({ path: 'env/.env' });
const connectDB = require('./database/DBConn')
const port = process.env.PORT || 5000;
const express = require('express')
const app = express()
// Connecting to DB
connectDB(()=>{
app.listen(port, () => {
console.log(`Backend : NodeJS/express server started on http://localhost:${port}`)
})
});
Another Way :
DBconn.js
const mongoose = require("mongoose");
require('dotenv').config({ path: 'env/.env' });
const dev_db_url = 'local dev. db url is not defined.';
const mongoDB_URL = process.env.MONGO_URL || dev_db_url;
const dbOptions = {useNewUrlParser: true, useUnifiedTopology: true};
const connectDB = async () => {
try {
await mongoose.connect(mongoDB_URL, dbOptions);
} catch (error) {
console.error("Could not Connect to Database", error)
}
};
module.exports = connectDB;
Server.js (here we use .once method)
require('dotenv').config({ path: 'env/.env' });
const mongoose = require("mongoose");
const connectDB = require('./database/DBConn')
const port = process.env.PORT || 5000;
const express = require('express');
const app = express();
connectDB();
mongoose.connection.once('open', () => {
console.log('Connected to MongoDB');
app.listen(port, () => {
console.log(`Backend : NodeJS/express server started on http://localhost:${port}`)
})
});

Await for function before end()

edit: added a bit more code.
const express = require('express');
var bodyParser = require('body-parser');
const app = express();
var urlencodedParser = bodyParser.urlencoded({extended: false})
const {google} = require('googleapis');
const {PubSub} = require('#google-cloud/pubsub');
const iot = require('#google-cloud/iot');
const API_VERSION = 'v1';
const DISCOVERY_API = 'https://cloudiot.googleapis.com/$discovery/rest';
app.get('/', urlencodedParser, (req, res) => {
const projectId = req.query.proyecto;
const cloudRegion = req.query.region;
const registryId = req.query.registro;
const numSerie = req.query.numSerie;
const command = req.query.command;
const client = new iot.v1.DeviceManagerClient();
if (client === undefined) {
console.log('Did not instantiate client.');
} else {
console.log('Did instantiate client.');
sendCom();
}
async function sendCom() {
const formattedName = await client.devicePath(projectId, cloudRegion, registryId, numSerie)
const binaryData = Buffer.from(command);
const request = {
name: formattedName,
binaryData: binaryData,
};
return client.sendCommandToDevice(request).then(responses => res.status(200).send(JSON.stringify({
data: OK
}))).catch(err => res.status(404).send('Could not send command. Is the device connected?'));
}
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
module.exports = app;
I have this function, that I call after the client initiate: sendCom();
async function sendCom() {
const formattedName = await client.devicePath(projectId, cloudRegion, registryId, deviceId)
const binaryData = Buffer.from(command);
const request = { name: formattedName, binaryData: binaryData, };
client.sendCommandToDevice(request)
.then(responses => {
res.status(200).send(JSON.stringify({ data: OK })).end();
})
.catch(err => {
res.status(404).send('Could not send command. Is the device connected?').end();
});
}
My problem is that sendCommandToDevice gets executed perfectly, however I get the catch error.
As I understand it, it's because in the .then ends the connection.
I've looked at this and thats's what I tried, however I'm not sure I understand what's going on.
You can not use send with end.
end() is used when you want to end the request and want to respond with no data.
send() is used to end the request and respond with some data.
You can found more about it here.

Strange Node await never unblocks

Node v8.3 + Express + using async / await complete source code below where await doesn't return unless I moved the terminal!!
// Express
const express = require('express');
const app = express();
// Lodash
const _ = require('lodash');
// DBR
const dbr = require('./build/Release/dbr');
dbr.initLicense("t0068MgAAAGvV3VqfqOzkuVGi7x/PFfZUQoUyJOakuduaSEoI2Pc8+kMwjrojxQgE5aJphmhagRmq/S9lppTkM4w3qCQezxk=");
// Promisify
const {promisify} = require('util');
const decodeFilePromise = promisify(dbr.decodeFileAsync);
app.get('/', async (req, res) => {
console.log("Received a barcode scan request!");
try {
const oneDimensionType = 0x3FF;
const scannedResults = await decodeFilePromise('test.jpg', oneDimensionType);
const imeiResults = _.uniq(_.map(_.filter(scannedResults, ['format', 'CODE_128']), 'value'));
console.log(`Successfully scanned the image: ${imeiResults}`);
res.send(`IMEI results: ${imeiResults}`);
}
catch (err) {
console.log(`Failed to scan the image: ${err}`);
res.send('Could not scan the barcode!');
}
});
app.listen(3000, () => {
console.log('Example app listening on port 3000!');
});
What do I mean by "unless I moved the terminal" ? Please see the attached GIF: https://youtu.be/HW_MqLzEC9M

Resources