I'm connecting to MongoDB from my Node.js.
If I start my connection from app.js file, then do I need to connect again from another JavaScript file, for example: from one of my models folder?
Here's my code for database.js:
const mongodb = require("mongodb");
const MongoClient = mongodb.MongoClient;
const mongoConnect = callback => {
MongoClient
.connect("mongodb+srv://<user>:<password>#node.idgpt.mongodb.net/myFirstDatabase?retryWrites=true&w=majority", {useUnifiedTopology: true})
.then(client => {
console.log("CONNECTED!!!");
callback(client);
})
.catch(err => {
console.log(err);
});
}
module.exports = mongoConnect;
Here's my code of app.js:
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const errorController = require('./controllers/error');
const mongoConnect = require('./util/database');
const app = express();
app.set('view engine', 'ejs');
app.set('views', 'views');
const adminRoutes = require('./routes/admin');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
mongoConnect(() => {
app.listen(3000);
});
So, my question is: Do I need to connect to MongoDB through mongoConnect function every time I want to perform CRUD operation? For example: if I want to insert data from another file which is in models folder, do I need to connect to MongoDB first and then execute the insert operation, because I already first connect to MongoDB from my app.js and then I start listening to my node server.
Note: I have replaced my username and password with <user> and <password> respectively.
provide sample code for more insights.
but if you connect in one file you can require this file in many files, it will always be the same connection.
Related
Whenever I make a post request, it shows that message is not a constructor. Here message is a model that I made using mongoose.
And I am exporting this model through
module.exports = message and using this exported model in form_post.js file
my app.js file
const express = require('express');
const app = express();
const path = require("path");
const mongoose = require('mongoose');
const port = 3000;
const form_display = require('./routes/form_display');
const form_post = require('./routes/form_post');
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
//Backend Connection
mongoose.connect("mongodb://127.0.0.1:27017/sudeepkart", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
var db = mongoose.connection;
db.once("open", function () {
console.log("We are Connected !!");
});
// Pug Specific
app.set('view engine', 'pug') //Setting View Engine as Pug
app.set('views', path.join(__dirname, 'views')) //Setting views directory so that pug files can be fetched from he views directory
// Express Specific
app.use(form_display);
app.use(form_post);
app.use('/static',express.static('static'))
app.use((req, res, next)=>{res.status(404).send('<h2>Error Page Not found</h2>')});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
})
my form_post.js file
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Message = require('../models/message.model')
const port = 3000;
router.use(express.urlencoded({ extended: false }))
router.use(express.json())
router.post('/message', function (req, res) {
// Creating New Object
var newMsg = new Message(req.body);
newMsg.save(function (err, msg) {
});
res.send('Your message has been successfully submitted');
})
module.exports = router;
my models/message.model.js file
const mongoose = require('mongoose');
// New Schema and New Model
var message_schema = new mongoose.Schema({ "id":String, "message":String });
var message = new mongoose.model("message_model", message_schema); // in other words model is a synonym for collection
module.exports = message;
Try destructuring it:
const {message} = require('../models/message.models')
MDN Documentation for destructuring
To answer your comment question, because you're trying to import Message while only exporting message. On your module.exports, I would reccomend always doing module.exports = {variable1, function2} etc, so you can destructure it and you can easily debug any issues (and stop confusion with variables too!)
i'm trying to build a simple rest api based on node.js + mongodb
i'm using https://cloud.mongodb.com/ and my connection string is 1000% correct
i keep having this problem sometimes it work for me all the day no issue
and sometimes it doesn't wanna connect and i changed nothing in the code
anyone is having similar issues?
const mongoose = require('mongoose');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
require('dotenv/config');
app.use(bodyParser.json());
// Import routes
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);
//mongodb connect
mongoose.connect(process.env.db_access, { useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log('connected');
}
);
//ROUTES
app.get('/', (req,res) => {
res.send('home boi');
});
//listening port
app.listen(3000);
I've started learning on MEAN development. I had setup my express server and also my mongodb connection. On running node server in terminal the server starts running and also the mongo was able to connect but the localhost:8081/api/videos is not loading. I cleared cache and cookies but still no solution. I am attaching the code below.
server.js
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const api = require('./server/routes/api');
// Port for express server
const port = 8081;
const app = express();
app.use(express.static(path.join(__dirname,'dist/mean')));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json);
app.use('/api', api);
app.get('*', (req,res)=> {
res.sendFile(path.join(__dirname, 'dist/mean/index.html'));
});
app.listen(port, function(){
console.log('Server running at localhost:' + port);
});
api.js
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Video = require('../models/video');
// Creating mongo db connection
const db = 'mongodb+srv://<username>:<password>#training-qfjgb.mongodb.net/test?retryWrites=true&w=majority';
mongoose.Promise = global.Promise;
mongoose.connect(db, { useUnifiedTopology: true, useNewUrlParser: true }, err => {
if(err) {
console.log('Error: '+err);
}
else {
console.log('Successfully connected to mongodb');
}
});
router.get('/videos', function(req, res){
console.log('Get request for all videos');
Video.find({}).exec(function(err, videos){
if(err)
{console.log('Error retrieving videos');}
else
{res.json(videos);}
});
});
module.exports = router;
video.js (This is for the schema)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Creating database schema
const videoSchema = new Schema({
title: String,
url: String,
description: String
});
// Creating model of database videoplayer as model and then exporting
module.exports = mongoose.model('video', videoSchema, 'videoplayer');
const db = 'mongodb+srv://username:password#training-qfjgb.mongodb.net/test?retryWrites=true&w=majority';
username:password should be changed.
admin:12345(as you using)
const db = 'mongodb+srv://username:password#training-qfjgb.mongodb.net/test?retryWrites=true&w=majority';
Check this part thoroughly , Whether the collection name, format of the text are given correctly
I started learning database with MongoDB and Node.js not long ago and I'm trying to find a way to use Express routes without mongoose. I want to insert data using Express routes and have clean code exporting different modules. The problem is that i can't write routes
as below because in my index.js file "db" is of course not defined and apparently i can't insert data into my "db" outside of the function "client.connect" as with mongoose. Do i have to connect my db in a file with all my posts or is there a specific way to do it? (sorry for my English, I'm learning it).
App.js :
const express = require('express');
const app = express();
const expressLayouts = require('express-ejs-layouts');
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
//EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');
//Styles
app.use('/public', express.static('public'));
//Bodyparser
app.use(express.urlencoded({extended: false}));
//Connect to DB
const url = 'mongodb://localhost:27017/shopping'
const dbName = 'shopping';
const client = new MongoClient(url);
client.connect((err)=>{
assert.equal(null, err);
console.log('connected to db...');
app.use('/', require('./routes/index'));
const db = client.db(dbName);
});
//Server
app.listen(3000, ()=>{console.log("Listening to port 3000")});
index.js (routes):
const express = require('express');
const router = express.Router();
//Get home page
router.get('/', (req, res)=>{
res.render('shop/index')
});
router.get('/posts', (req,res)=>{
res.render('posts')
});
router.post('/posts',(req,res)=>{
db.collection('users').insertOne({'name': req.name, 'password': req.password});
});
module.exports = router;
Index.js should include a function with which to pass your mongo client in. So for example:
let mongoClient
router.passMongoClient = function(clientIn){
mongoClient = clientIn
}
Then after you've started your client, pass it in through your new function
const router = require(./router)
client.connect((err)=>{
assert.equal(null, err);
console.log('connected to db...');
app.use('/', require('./routes/index'));
const db = client.db(dbName);
router.passMongoClient(db)
});
This is the basic idea. You may wish to structure your code a little differently. I wait to start my http server until I get the callback from the mongodb client that it's connected. Depends on your use case to a degree.
in my index.js file:
const express = require('express');
const router = express.Router();
// Do work here
router.get('/', (req, res) => {
res.send('Hey! It works!');
});
module.exports = router;
I am able to make the first request just fine, but every subsequent request just waits for localhost until it times out.
app.js looks like:
const express = require('express');
const session = require('express-session');
const mongoose = require('mongoose');
const MongoStore = require('connect-mongo')(session);
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const passport = require('passport');
const promisify = require('es6-promisify');
const flash = require('connect-flash');
const expressValidator = require('express-validator');
const routes = require('./routes/index');
const helpers = require('./helpers');
const errorHandlers = require('./handlers/errorHandlers');
// create our Express app
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views')); // this is the folder where we keep our pug files
app.set('view engine', 'pug'); // we use the engine pug, mustache or EJS work great too
// serves up static files from the public folder. Anything in public/ will just be served up as the file it is
app.use(express.static(path.join(__dirname, 'public')));
// done! we export it so we can start the site in start.js
module.exports = app;
the start.js file looks like this. I should add that this is not my own code - it's part of the node.js tutorial from Wes Bos.
const mongoose = require('mongoose');
// import environmental variables from our variables.env file
require('dotenv').config({ path: 'variables.env' });
// Connect to our Database and handle any bad connections
mongoose.connect(process.env.DATABASE);
mongoose.Promise = global.Promise; // Tell Mongoose to use ES6 promises
mongoose.connection.on('error', (err) => {
console.error(`🙅 🚫 🙅 🚫 🙅 🚫 🙅 🚫 → ${err.message}`);
});
// READY?! Let's go!
// Start our app!
const app = require('./app');
app.set('port', process.env.PORT || 7777);
const server = app.listen(app.get('port'), () => {
console.log(`Express running → PORT ${server.address().port}`);
});
Managed to solve my own problem, so I'm reporting back for anyone who may have encountered the same issue coming from the Wes Bos Node.js tutorial.
The solution was to double check my variables.env file - I had stupidly left arrow brackets around the username and password fields. If you're having this issue, make sure your DATABASE environment variable looks something like this:
DATABASE=mongodb://dang:dang#ds057833.mlab.com:57833/dang-thats-delicious