What does 'dbo' stands for in MongoDB - Express app? - javascript

Here is the code example:
app.js
const express = require("express");
const app = express();
const cors = require("cors");
require("dotenv").config({ path: "./config.env" });
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.use(require("./routes/record"));
// get driver connection
const dbo = require("./db/conn");
app.listen(port, () => {
// perform a database connection when server starts
dbo.connectToServer(function (err) {
if (err) console.error(err);
});
console.log(`Server is running on port: ${port}`);
});
db/conn.js
const { MongoClient } = require("mongodb");
const Db = process.env.ATLAS_URI;
const client = new MongoClient(Db, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
var _db;
module.exports = {
connectToServer: function (callback) {
client.connect(function (err, db) {
// Verify we got a good "db" object
if (db)
{
_db = db.db("employees");
console.log("Successfully connected to MongoDB.");
}
return callback(err);
});
},
getDb: function () {
return _db;
},
};
I've done some research and it stands for 'Database Owner' in SQL Server but it doesn't make sense here.
These code examples are from MongoDB official documentation and why do they assign connection instance as dbo if it really stands for Database Owner?

As the documentation provides no explanation for the choice of variable name, we can only guess. My best guess is that dbo stands for database object, considering the type of the export.

I think this is idiosyncratic usage mimicked from the SQL world where dbo is the default schema and abbreviates database owner.
Typically, and in the MongoClient documentation, I see just db = require("./db/conn"); But it appears here that the author's fingers are just used to automatically typing an o after typing db.
Humans are habitual imitators. I wouldn't think too much of it. It's just a variable name.

There is no restriction and built-in parameters name in nodejs.
You can use that according to your preference

Related

express API extract data from URL

My api recives every 45 minutes a request:
GET http://MyHost/mediciones/sigfox_libelium/{device}/{data}/{time}/{customData#trama}
I want my code to save {device}, {data}, {time} and {customData#trama} into different variables so I can parse it into readable values(all data it is send hexadecimal) and insert them into my database.
How do I take those values out of the URL?
Also, what is the purpose of req, res? I guess It stands for request, respond.Respond sends back to the client but, request? I dont really understand how it works. Im learning all this new, hope someone can help.
This is my API code, I tried it with postman and it works fine so far:
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const Pool = require("pg").Pool;
const pool = new Pool({
user: "mgr#stanpgtest",
host: "stanpgtest.postgres.database.azure.com",
database: "my db name",
password: "my pass",
port: 5432
});
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.listen(8000, () => {
console.log(`Server is running, listening to port 8000`);
});
app.post("mediciones/sigfox_libelium/{device}/{data}/{time}/{customData#trama}", (req, res) => {
const { label, status, priority } = req.body;
pool.query(
"select now()",
(error, results) => {
if (error) {
throw error;
}
res.send(results);
}
);
});
You need to write the path in this format, then extract your params from req.params.
app.post("mediciones/sigfox_libelium/:device/:data/:time/:customData", (req, res) => {
const {device, data, time, customData} = req.params
}
I'm not sure what #trama is meant to be, but I guess you can't use # in the route pattern.

Cant connect to MongoDB in Firebase Functions

I am using Firebase Functions as the host for my MERN web app backend.
When I connect to MongoDB locally, it works and can run operations with the database. However, when I deployed to firebase functions, it failed to even connect to the database.
Code:
index.js
const functions = require('firebase-functions');
const server = require('./server.js');
exports.api = functions.runWith({ memory: "2GB", timeoutSeconds: 120 }).https.onRequest(server);
Part of server.js
const express = require("express");
const dotenv = require("dotenv");
const colors = require("colors");
const morgan = require("morgan");
const path = require("path");
const cors = require("cors");
const bodyParser = require("body-parser");
const routes = require("./routes/routes.js");
const mongooseMethods = require("./database.js");
dotenv.config({ path: "./config/config.env" });
mongooseMethods.connectDB(process.env.MONGO_URL);
const PORT = process.env.PORT || 8080;
// set up app
const app = express();
app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold));
app.use(cors({ origin: true }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan("dev"));
app.use("/api", routes); // /api routes
module.exports = app;
routes.js
const express = require("express");
const app = express.Router();
const testingApi = require('../controller/testing.js');
const authApi = require('../controller/auth.js');
// testing
app.get('/testing', testingApi.testing);
// user authentication
app.post('/user/register', authApi.createUser);
module.exports = app;
api/testing/ also works
database.js
const mongoose = require("mongoose");
const mongooseMethods = {
connectDB: async (url) => {
try {
console.log("Connecting to MongoDB")
const connection = await mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });
console.log(`MongoDB Connected: ${connection.connection.host}`.cyan.bold);
return connection;
} catch (error) {
console.log(`Error: ${error.message}, Exiting`.red.bold);
process.exit(1);
}
}
}
module.exports = mongooseMethods;
auth.js
const User = require('../model/user.model.js');
const bcrypt = require("bcryptjs");
let authenticationApi = {
createUser: async (req, res) => {
try {
console.log("Creating");
let newUser = new User({
...req.body
})
let result = await newUser.save();
return res.status(200).json({ result: result });
} catch (error) {
return res.status(400);
}
}
}
module.exports = authenticationApi;
The error I received when sending request to firebase is
2020-02-27T02:34:46.334044912Z D api: Function execution took 30970 ms, finished with status: 'connection error'
Yet it runs perfectly fine in local. I also don't see the console log "connected to MongoDB". I'm guessing that the problem occurs in database.js that it failed to connect to mongo at the first place yet I don't know how to solve.
I am using the paid plan in Firebase and the outbound networking should be fine.
p.s. this is my first time posting here. thanks for your time and I apologize in advance if i'm breaking any rules.
Listening on a port is not a valid operation in cloud functions:
app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold));
Cloud Functions listens for you, using the URL that it was assigned, then delivers the request to your code. When you pass your express app to onRequest(), that's all wired up for you.
I suggest starting with a stripped down, simplified version of an app just to gain experience about how things work, then add in more as you get comfortable.
The reason for this to happen is that the architecture of Firebase Functions is not an actual server, but a serverless lambda-like endpoint. Since it cannot establish a lasting connection to the database, that it has to make a connection every time it received a request, the database sees this as spam and shut down further connection request from Firebase.
Therefore, you simply cannot host a complete express app with intended lasting connection in Firebase Functions.
More on that in this article

cannot connect to mongo local DB from Node JS

I am learning Mongo DB, Mongoose and Node JS and I can't seem to connect my Node JS to local Mongo DB.
Here is my code:
dbtest.js
var express = require('express');
var app = express(); // create our app w/ express
var mongoose = require('mongoose'); // mongoose for mongodb
var morgan = require('morgan'); // log requests to the console (express4)
var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var options = {
useMongoClient: true,
autoIndex: false, // Don't build indexes
reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
reconnectInterval: 500, // Reconnect every 500ms
poolSize: 10, // Maintain up to 10 socket connections
// If not connected, return errors immediately rather than waiting for reconnect
bufferMaxEntries: 0
};
var Todo = mongoose.model('Todo', {
text : String
}, 'test');
var status = {
"status": "not connected"
};
app.get('/api/todos', function(req, res) {
mongoose.connect('mongodb://127.0.0.1:27017/exampleDB',options,function(err)
{
if (err) {
res.json(status);
} else {
res.json('Connected');
}
});
});
app.listen(8080);
console.log("App listening on port 8080");
When I call api/todos GET request, the status JSON object is returned, meaning I cannot connect to the database.
I installed MongoDB Enterprise Server 3.14.10 completely and have it running but I don't know why my NodeJS application cannot connect.
Any suggestions are appreciated.
Your first mongoose.connect() argument lacks username / password combination:
mongoose.connect('mongodb://username:password#127.0.0.1:27017/exampleDB');
Try to connect db first before doing any action. Once it connected try to use inside your custom function. Below code will helps you to test local database
const express = require('express');
const app = express();
const port = 3000;
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/dbname', { useMongoClient: true });
mongoose.connection.on('connected', () => {
console.log('Connected to database ');
});
mongoose.connection.on('error', (err) => {
console.log('Database error: '+err);
});
// Start Server
app.listen(port, () => {
console.log('Server started on port '+port);
});
Check your cmd window to see console.
For connecting to a local mongodb, you can use this URI, replacing USER, PASSWORD are DB with your values :
mongodb://USER:PASSWORD#127.0.0.1/DB?authSource=admin
You don't need to provide the port 27017, because it's the default one for mongodb.
The trick here is to add with 'authSource=admin' for enabling the authentication.
Documentation :
https://docs.mongodb.com/manual/reference/connection-string/#examples

Could somebody explain how to pass globally the database variable in express.js?

already tried a lot of tutorials, but somehow I could not figure it out.
I am using mongodb and express.js
this is in my server.js
const express = require('express');
const subdomain = require('express-subdomain');
const bodyParser= require('body-parser');
const MongoClient = require('mongodb').MongoClient;
const routes = require('./routes');
const app = express();
var db;
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('views'));
app.use(subdomain('api', routes.api));
MongoClient.connect('mongodb://localhost:27017/test', (err, database) => {
if (err) return console.log(err);
db = database;
app.listen(3000, () => {
console.log('listening on 3000');
});
});
and this is in my routes.js
const express = require('express');
const api = express.Router();
api.get('/', function (req, res) {
db.collection('test').find().toArray((err, result) => {
if (err) return console.log(err);
res.render('api_orders', {test: result});
});
});
module.exports = {
api
}
I would like to use the db variable also in routes, but it always gives me the db is not defined error (obviously) I read that I should somehow export the db var, but could not managed to do it
Instead i would suggest you to create another file and you just require it where you want to use it. Suppose:
db.js:
const MongoClient = require('mongodb').MongoClient;
const db = function(){
return MongoClient.connect('mongodb://localhost:27017/test', (err, database) => {
if (err) return console.log(err);
return database;
});
}
module.exports = db;
Now you can use the db anywhere when you do :
const mydb = require('./db'); // <--require it to use
It may not work as it is not tested but it can give you idea to get through.
This is as much a question as a response. I've used
MongoClient.connect('mongodb://localhost:27017/test', (err, database)={
global.bigdb = database
});
and called it from the routes for instance
var col = global.bigdb.collection('collectionname');
Is this bad practice? Rereading the code - it's been live for a while - I'm also exposing the redis client as a global.
Any info appreciated. Live with no bug reports but very curious if I should refactor.
app.use(function(req,res,next))
{
res.locals.yourvariable = null;
next();
});
This is how I initialize global variables. Hope you get an idea.

Can not establish mongodb connection from node js

I made this node js app and then i tried with postman but every time i made a request that involves mongodb, it keeps loading. The function find of the model is where the code stops and the callback is never called.
app.js
var express = require("express"),
app = express(),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
mongoose = require('mongoose');
//Connection to DB
mongoose.connect('mongodb://localhost:27017/users', function(err, res) {
if(err) {
console.log('ERROR: connecting to Database. ' + err);
}
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
var models = require('./models/user')(app, mongoose);
var userContoller = require('./controllers/user');
var router = express.Router();
router.get('/', function(req, res) {
console.log('GET');
res.send("Hello World!");
});
app.use(router);
var users = express.Router();
users.route('/users')
.get(userContoller.findAllUsers);
app.use('/api', users);
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
models/user.js
exports = module.exports = function(app, mongoose){
var userSchema = new mongoose.Schema({
userName: { type: String },
password: { type: Number }
});
mongoose.model('User', userSchema);
};
controllers/user.js
var mongoose = require('mongoose');
var User = mongoose.model('User');
//GET - Return all tvshows in the DB
exports.findAllUsers = function(req, res) {
console.log('llega');
User.find(function(err, users) {
if(err) res.send(500, err.message);
console.log('GET /users')
res.status(200).jsonp(users);
});
};
The mongodb server is started through the console but i don't know how to check it.
Thanks!
EDIT:
I made the code easier for me to test and solve the problem.
The code now is this and im not getting the connection to mongodb.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', function() {
console.log('error');
});
db.once('open', function() {
console.log('connected');
});
I don't get in the console the error or the connected.
In the mongod console i get some messages saying that a new connection was made. This happens every time i open the nodejs program.
Thanks
I think the problem is that you are giving call back to the mongoose.connect function. In my case i did:
mongoose.connect(url, options)
const db = mongoose.connection
db.on('error', function () { console.log('Cannot Connect to DB') })
db.once('open', function () { console.log('Mongoose Connected to DB') })
Also instead of:
users.route('/users').get(userContoller.findAllUsers);
You may try:
users.get('/users', userController.findAllUsers);
And I realized that you don't pass a next argument to your controller which express generally complains if you dont pass.
Edit: I think i found the error.
When you are using the .find function you need to pass 2 arguments. In your case because you are not passing the callback as the second argument it never gets called.
User.find({}, callback) should do it.
I found the problem.
The version of mongoose was older than the needed to connect to my mongodb version. Just update it via npm and good to go.

Categories

Resources