I'm building an application on Node.js that works with MongoDB through mongoose. The connection is perfect, I can add new documents, the problem is definitely not in the connection.
I'm building all the functions that work with mongoose in a separate .js file, which I called from dbconfig.js.
dbconfig.js
const mongoose = require('mongoose');
// Models
const User = require('./models/User');
const Category = require('./models/Category');
var database_name = "htm";
mongoose.Promise = global.Promise;
// Connection with database_name
var connect = () => {
mongoose.connect("mongodb://localhost/"+database_name, {useNewUrlParser: true}).then(() =>{
console.log("Conectado ao database: " + database_name);
}).catch((erro) => {
console.log("Erro ao se conectar ao database: " + database_name +" - "+ erro);
});
mongoose.model('users', User);
mongoose.model('categories', Category);
}
var getCategory = () => {
const Ref = mongoose.model('categories');
Ref.find().then((categories) => {
return categories;
})
}
module.exports = {
connect: connect,
getCategory: getCategory
}
The problem is in the getCategory () function, when I call it in my app.js (my main file of this project node.js), it returns only undefined. And I know that the variable categories are filled out because I inserted a console.log (categories); and got the following result:
[ { _id: 5c7ea6fb91526418ec3ba2fd,
name: 'UNHAS',
slug: 'unhas',
__v: 0 } ]
app.js
const express = require('express');
const app = express();
const categoriesRouter = require('./routes/categories');
const handlebars = require('express-handlebars');
const path = require('path');
const configDB = require('./dbconfig')
// Config
// Template Engine
app.engine('handlebars', handlebars({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
// Start Database Connection
configDB.connect();
// Public
app.use(express.static(path.join(__dirname, "public")));
// Routes
app.use('/categorias', categoriesRouter);
app.get('/', (req, res) => {
var categories = configDB.getCategory();
res.render('home', categories);
});
app.listen(3001, () =>{
console.log("Servidor iniciado na porta 3001");
});
Whenever the variable categories is received in my app.js it arrives as undefined.
Can someone help me?
You are not properly using the Promise object returned from getCategory() in your express router:
app.get('/', (req, res) => {
var categories = configDB.getCategory(); <-- this is a Promise, not a synchronous value
res.render('home', categories);
});
Instead, you can use async/await to help bridge the gap between your currently synchronous code and the asynchronous Promise-based database interface you have:
app.get('/', async (req, res) => {
var categories = await configDB.getCategory();
res.render('home', categories);
});
Inspired by a response given by #jakemingolla who suggested async-await, I started using callback to return the 'categories' object and everything worked perfectly.
function in my file dbconfig.js
const getCategoryList = (callback) => {
CategoryRef.find().then((categories) => {
callback(categories);
})
}
calling the function in my app.js file
app.get('/', (req, res) => {
database.getCategoryHomeList((categories) => {
res.render('home', {categories: categories});
})
});
Related
I am having trouble being able to insert data into my collection, I'm not even sure I'm doing it correctly so I apologize for the vague request but maybe my code will help you see what my intention is. The gist of it is I'm trying to make a separate file for my schema/collection and then call it from another file and insert data and call other functions etc.
file1.js file:
require('dotenv').config()
const User = require('./assets/js/data')
const bodyParser = require("body-parser");
const mongoose = require('mongoose');
mongoose.connect(process.env.url, { useNewUrlParser: true })
.then(() => {
console.log('Connected to MongoDB server');
})
// 1. Import the express module
const express = require('express');
// 2. Create an instance of the express application
const app = express();
app.set('views', './static/html');
app.set('view engine', 'ejs');
app.use(express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// 3. Define the HTTP request handlers
app.get('/', (req, res) => {
res.render('main')
});
app.get('/login', (req, res) => {
res.render('login')
});
app.post('/login', (req, res) => {
console.log(req.body.number);
})
app.listen(3000, (err) => {
console.log("running server on port")
if (err) {
return console.log(err);
}
})
data.js
const mongoose = require('mongoose');
const userData = new mongoose.Schema({
phoneNumber: String,
})
const User = mongoose.model('User', userData);
module.exports(
User,
)
This line has the error.
// error
module.exports(
User,
)
module.exports is not a function.
module.exports = User
// or
module.exports = { User }
if you do the first one, then required should be like this,
const User = require('./assets/js/data')
otherwise
const { User } = require('./assets/js/data')
More about module.exports
The Data.js is correct but the way your controller works is I think the issue. If you use "const User = require('./assets/js/data')" you can use your selected variable User and then connect find, create, etc. you can use this as a reference. https://blog.logrocket.com/mern-stack-tutorial/
I'm currently learning about APIs. I'm using Dev Ed's video on a RESTful MERN API. I set up my routes and I could successfully connect to my MongoDB database. However, when attempting to call save() on a post to the DB, I was returned my error message, a JSON object with a message containing the err, but my err object was completely empty.
posts.js:
const express = require('express');
const router = express.Router();
const Post = require('../models/Post');
router.get('/', (req, res) => {
res.send('We are on /posts!');
});
router.post('/', (req, res) => {
const post = new Post({
title: req.body.title,
desc: req.body.desc,
});
post.save()
.then(data => {
res.json(data);
})
.catch(err => {
res.json({ message: err });
});
});
module.exports = router;
app.js:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv/config');
const app = express();
const PORT = 8080;
app.use(bodyParser.json());
// Import Routes ------------------------
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);
// ROUTES --------------------------------
app.get('/', (req, res) => {
res.send('We are home!');
});
mongoose.connect(
process.env.DB_CONN,
{ useNewUrlParser: true },
() => {
console.log('Succesfully connected to DB!')
});
app.listen(PORT);
Post.js (schema):
const mongoose = require('mongoose');
const PostSchema = mongoose.Schema({
title: {
type: String,
required: true,
},
desc: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
}
});
module.exports = mongoose.model('Posts', PostSchema);
My POST request and response (Postman):
In my code, I am attempting to send the new Post to my DB, but instead I get an error, an empty one. I either need to figure out how to view my error correctly (so that's it's not empty) or the larger problem: why my POST request is failing.
Again, I am learning about APIs, this is my very first time writing one. If there's anything I missed (like other code that you would need) or if there's something I should be doing differently, please, let me know! Thank you in advance!
use status when you want to use res like this:
for success result
res.status(200).json(data);
for .catch
res.status(500).json({ message: err });
but I prefer use async/await with try/cacth like this:
router.post('/', async(req, res) => {
const post = new Post({
title: req.body.title,
desc: req.body.desc,
});
try {
let data = await post.save()
res.status(200).json(data)
} catch (error) {
res.status(500).json({ message: error});
}
});
check the documentation of promises in mongnoos
check the connection of mongoose like this:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv/config');
const app = express();
const PORT = 8080;
app.use(bodyParser.json());
// Import Routes ------------------------
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);
// ROUTES --------------------------------
app.get('/', (req, res) => {
res.send('We are home!');
});
runMongoose()
app.listen(PORT);
async function runMongoose(){
try {
await mongoose.connect(
process.env.DB_CONN,
{ useNewUrlParser: true }
);
console.log("mongodb is OK");
} catch (error) {
console.log("mongodb Warning", error);
}
}
if Succesfully connected to DB! printed mongoose connection is OK
the problem is that you added
{ useNewUrlParser: true }
remove that and it's gonna work fine ;)
i'm trying to pass the mongodb connection to all the other routes, so i created another file and imported mongoClient there and wrapped connect and getDb in functions so i can connect to the db first from server.js and then access the db from the other files, but idk why i'm getting Cannot read property 'collection' of undefined
server.js
const express = require('express')
const bodyParser = require('body-parser')
const mongodb = require('./mongodb/db.js')
const auth = require('./routes/auth.js')
require('dotenv').config()
const app = express();
app.use(bodyParser.json());
const PORT = process.env.PORT
app.get('/api', (req, res) => {
res.send('Welcome to the api')
})
app.use('/api/auth', auth);
mongodb.connect(() => {
app.listen(PORT, () => {
console.log(`app is listening at http://localhost:${PORT}`)
})
})
./mongodb/db.js
const MongoClient = require('mongodb').MongoClient;
const DB_URL = process.env.DB_URL
const DB_NAME = process.env.DB_NAME
const dbClient = new MongoClient(DB_URL, { useUnifiedTopology: true })
let db;
const connect = (callback) => {
dbClient.connect().then(client => {
db = client.db(DB_NAME)
console.log("connected to db")
}).catch(console.log)
callback()
}
const get = () => {
return db;
}
module.exports = {
connect,
get
};
./routes/auth.js
const express = require('express')
const router = express.Router();
const db = require('../mongodb/db.js');
const smth = db.get();
console.log(smth) //undefined;
const usersCollection = db.get().collection('users');
const authCollection = db.get().collection('auth')
router.post('/login', async (req, res) => {
...
})
router.post('/register', async (req, res) => {
...
})
module.exports = router
You call callback outside of the promise chain in the connect function of ./mongodb/db.js. It's possible that you are running into some async issues there, as the function can return before the promise chain resolves.
I am creating nodejs backend app with postgresql database. What I want is when once I create connection to database in my db.js file, that I can reuse it in other files to execute queries.
This is my db.js file
const pool = new Pool({
user: 'us',
host: 'localhost',
database: 'db',
password: 'pass',
port: 5432,
})
pool.on('connect', () => {
console.log('connected to the Database');
});
module.exports = () => { return pool; }
And this is how I tried to use it in index.js file
const db = require('./db.js')
app.get('/', (request, response) => {
db().query('SELECT * FROM country'), (error, results) => {
if (error) {
response.send(error)
}
console.log(results)
response.status(201).send(results)
}
})
There aren't any errors, and when I go to this specific page, it's keep loading. Nothing in console also.
But, if I write a function in my db.js file and do something like pool.query(...), export it, and in my index.js I write app.get('/', exportedFunction), everything is working fine.
Is there any way not to write all my (like 50) queries in just one (db.js) file, because I want to organise my project a little bit?
To streamline your project structure entirely, if you're starting from scratch maybe try this :
index.js
const express = require('express');
const app = express();
const PORT = 8080;
const bodyparser = require('body-parser');
const baseRouter = require('../your-router');
app.use(bodyparser.json());
app.use(express.json());
app.use('/', baseRouter);
app.listen(PORT, function () {
console.log('Server is running on PORT:', PORT);
});
your-router.js
const Router = require('express');
const router = Router();
const getCountries = require('../handlers/get');
router.get('/check-live', (req, res) => res.sendStatus(200));
// route for getCountries
router.get('/countries', getCountries);
src/handler/get.js
const YourService = require('./service/your-service');
function getCountries(request, response) {
const yourService = new YourService();
yourService.getCountries(request)
.then((res) => { response.send(res); })
.catch((error) => { response.status(400).send({ message: error.message }) })
}
module.exports = getCountries;
src/service/your-service.js
const connectionPool = require('../util/dbConnect');
class yourService {
getCountries(req) {
return new Promise(((resolve, reject) => {
connectionPool.connect((err, db) => {
if (err) reject(err);
let query = format('SELECT * FROM country'); // get inputs from req
db.query(query, (err, result) => {
if (err) reject(err);
resolve(result);
})
});
}));
}
}
module.exports = yourService;
dbConnect.js
const pgCon = require('pg')
const PGUSER = 'USER'
const PGDATABASE = 'localhost'
let config = {
user: PGUSER,
database: PGDATABASE,
max: 10,
idleTimeoutMillis: 30000
}
let connectionPool = new pgCon.Pool(config);
module.exports = connectionPool;
Please consider this as a basic example, refactor your code to use callbacks/async awaits (in the above example you can just use callbacks not needed to convert into promise), if needed - you can have DB-layer calls from the service layer in order to extract DB methods from the service layer.
I have several mongodb collections,
Fruits: [ {}, {}, {} ...],
Bread: [{}, {}, {} ...]
I want to use dynamic collection name in my server like
// :collection will be "Fruits" or "Bread"
app.get('/fetch/:collection', function (req, res){
[req.params.collection].find({}, function(err, docs){
res.json(docs)
})
})
But as you know, [req.params.collection].find()... isn't working. How can I use dynamic collection name?
You can use the different collections using
db.collection('name').find({})
Here is the code i have tried
App.js
const express = require('express');
const bodyParser = require('body-parser');
const MongoClient = require("mongodb").MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
var db;
MongoClient.connect(url, { useNewUrlParser: true }, function (err, client) {
assert.equal(null, err);
console.log("Connected successfully to DB");
db = client.db('name of the db');
});
var app=express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/test/:collection', function(req,res){
let collection = req.params.collection;
console.log(collection);
db.collection(collection).find({}).toArray( function (err, result) {
res.send(result);
});
});
var port = 8000
app.listen(port, '0.0.0.0', () => {
console.log('Service running on port ' + port);
});
Hope this helps
This is not working as the collection name you are passing is just a variable with no DB cursor.
Here's what you can do here:
Create an index.js file, import all the models in that file with proper names as keys.
eg:
const model = {
order: require("./order"),
product: require("./product"),
token: require("./token"),
user: require("./user")
}
module.exports = model;
Let's assume your request URL is now.
/fetch/user
Now import this index.js as model in your controller file.
eg:
const model = require("./index");
Now you can pass the key as params in your request like and use like it is stated below:
app.get('/fetch/:collection', function (req, res){
model[req.params.collection].find({}, function(err, docs){
res.json(docs) // All user data.
})
})
Hope this solves your query!
I will give solution for this but I don't know is this as per developer standards
let your model names, fruit.js and bread.js in model folder
app.get('/fetch/:collection', function (req, res){
let collectionName = require(`./models/${req.params.collection}`)
collectionName.find({}, function(err, docs){
res.json(docs)
})
})
Hope this will work