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
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 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});
})
});
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.
Am merging 2 different applications one is an authentification app and the other is a todo app where user input data and the app displays it. The two work fine seperately. when i merged them there is a parse error on the second app; I think i got the issue. the authentification app uses app.use(bodyParser.json()); and the second one uses app.use(bodyParser()); I think there is a conflict but i dont know how to solve it can you help
here is my api
var Meetup = require('./models/meetup');
module.exports.create = function (req, res) {
var meetup = new Meetup(req.body);
console.log(req.body);
meetup.save(function (err, result) {
console.log(result);
res.json(result);
});
}
module.exports.list = function (req, res) {
Meetup.find({}, function (err, results) {
res.json(results);
});
}
console.log(req.body) displays undefined.
console.log(result) displays { __v: 0, _id: 583464c837cb810e045b1825 } while it should display { __v: 0,name:'text input' _id: 583464c837cb810e045b1825 }
here is my schema model :
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Meetup = new Schema({
name: String,
text:String,
});
module.exports = mongoose.model('Meetup', Meetup);
The bodyParser() constructor is deprecated.
You should use this instead:
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());