I am trying to run my webapp using mongodb but I am constantly getting error of app crashed. I have rechecked everything but it is still causing error. Can anyone help me with it?
server.js:
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config()
}
const express = require('express')
const app = express()
const expressLayouts = require('express-ejs-layouts')
const indexRouter = require('./routes/index')
const authorRouter = require('./routes/authors')
app.set('view engine', 'ejs')
app.set('views', __dirname + '/views')
app.set('layout', 'layouts/layout')
app.use(expressLayouts)
app.use(express.static('public'))
const mongoose = require('mongoose')
mongoose.connect(process.env.DATABASE_URL, { useNewUrlParser: true })
const db = mongoose.connection
db.on('error', error => console.error(error))
db.once('open', () => console.log('Connected to Mongoose'))
app.use('/', indexRouter)
app.use('/authors', authorRouter)
app.listen(process.env.PORT || 3000)
author.js
const mongoose = require('mongoose')
const authorSchema = new mongoose.Schema({
name: {
type: String,
required: true
}
})
module.exports = mongoose.model('Author', authorSchema)
I have separate folder for routes for authors. The above author is author model and this one file is for /authors route.
authors.js:
const express = require('express')
const router = express.Router()
const Author = require('../models/author')
// All Authors Route
router.get('/', (req, res) => {
res.render('authors/index')
})
// New Author Route
router.get('/new', (req, res) => {
res.render('authors/new', { author: new Author() })
})
// Create Author Route
router.post('/', (req, res) => {
res.send('Create')
})
module.exports = router
I get this error
[nodemon] app crashed - waiting for file changes before starting...
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 using Node.js to make a networking app equipped with a database and I keep getting an error message:
Error: connect ETIMEOUT,
app.js
const express = require('express')
const mysql = require('mysql')
const dotenv = require('dotenv')
const path = require('path')
const cookieParser = require('cookie-parser')
const app = express()
dotenv.config({path:'./.env'})
app.set('view engine', 'hbs')
const publicDirectory = path.join(__dirname, './public')
app.use(express.static(publicDirectory))
app.use(express.urlencoded({extended: false}))
app.use(express.json())
app.use(cookieParser())
const db = mysql.createConnection({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
database: process.env.DATABASE,
password: process.env.DATABASE_PASSWORD
})
db.connect( (error) => {
if(error){
console.log(error)
}else{
console.log('DB Connected!')
}
})
app.use('/', require ('./routes/pages'))
app.use('/auth', require ('./routes/auth'))
app.listen(5000, () => {
console.log('Your Connected To Port 5000')
})
I store most of my important info in a .env file for security purposes
.env
DATABASE = bullshit
DATABASE_USER = username
DATABASE_HOST = 192.168.1.3
DATABASE_PASSWORD = password
JWT_SECRET = mysupersecretpassword
JWT_EXPIRES_IN = 90d
JWT_COOKIE_EXPIRES = 90
auth.js
const express = require('express')
const authController = require('../controllers/auth')
const router = express.Router()
router.post('/register', authController.register)
router.post('/login', authController.login)
module.exports = router
pages.js
const express = require('express')
const router = express.Router()
router.get('/', (req,res) => {
res.render('index')
})
router.get('/register', (req,res) => {
res.render('register')
})
router.get('/login', (req,res) => {
res.render('login')
})
router.get('/profile', (req,res) => {
res.render('profile')
})
module.exports = router
someone told me to change the host to my ip address and so I did. But when I did that's when I got the ETIMEOUT error message. PLEASE HELP
I'm making a GridView in Node.js, But, It's Not connecting to Mongoose and Creating the DB. When I write
show dbs
In my Mongo Shell Then I don't get my Database Created.
This is my Code
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const ejs = require("ejs");
const app = express();
const port = 80;
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
mongoose.connect("mongodb://localhost:27017/griData", {useNewUrlParser: true, useUnifiedTopology: true}, (err)=> {
if(err){
console.log(err);
}
});
console.log(mongoose.connection.readyState);
app.get("/", (req, res)=> {
res.render("main");
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
The database will be created when you will add a first document in the collection automatically.
I am creating an application using expressjs, mongoose and ejs template engine.
I am facing an below mentioned issue while saving collection:
{"message":"Invalid namespace specified 'ecommerce\";.roleresources'"}
This is my entry script app.js file:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const expressLayout = require('express-ejs-layouts');
const config = require('./config');
const adminRoutes = require('./routes/admin');
const app = express();
// set the view engine to ejs
app.set('view engine', 'ejs');
app.set('views', 'views');
app.set('layout', 'layout/shop');
app.set("layout extractScripts", true)
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressLayout);
app.use(express.static(path.join(__dirname, 'public')));
app.use('/admin', adminRoutes);
mongoose.Promise = global.Promise;
mongoose
.connect(config.mongodb_uri, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex:true } )
.then(result => {
console.log(result);
app.listen(config.port || 3000);
})
.catch(err => {
process.exit();
});
These are file config.js file:
const dotenv = require('dotenv');
dotenv.config();
module.exports = {
port:process.env.PORT,
mongodb_uri: process.env.MONGODB_URI
}
and this is my .env file:
PORT=3000
MONGODB_URI="mongodb://localhost:27017/ecommerce";
and model file is:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const roleResourceSchema = Schema({
name:{
type:String,
required:true
},
code:{
type:String,
required:true
},
url:{
type:String,
required:true
}
});
roleResourceSchema.index({name:1, code:1,url:1}, {unique:true});
module.exports = mongoose.model('RoleResource', roleResourceSchema);
and lastly my controller:
const RoleResource = require('../model/roleResource');
exports.getLogin = (req, res, next) => {
const resource = new RoleResource({
name:"All",
code:"all",
url:"*",
});
resource.save()
.then(data => {
res.send(data);
}).catch(err => {
res.status(500).send({
message: err.message
});
});
};
and if hard coded the mongodb url in my app.js then it's start working (modified app.js for working mongoose save)
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const expressLayout = require('express-ejs-layouts');
const config = require('./config');
const adminRoutes = require('./routes/admin');
const app = express();
// set the view engine to ejs
app.set('view engine', 'ejs');
app.set('views', 'views');
app.set('layout', 'layout/shop');
app.set("layout extractScripts", true)
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressLayout);
app.use(express.static(path.join(__dirname, 'public')));
app.use('/admin', adminRoutes);
mongoose.Promise = global.Promise;
mongoose
.connect("mongodb://localhost:27017/ecommerce", { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex:true } )
.then(result => {
console.log(result);
app.listen(config.port || 3000);
})
.catch(err => {
process.exit();
});
How can I dynamically use the mongo db url from my .env file
It took me a while to resolved mine, but i finally did.
In you .env file, remove the quotes in MONGODB_URI.
Check sample below
PORT=3000
MONGODB_URI=mongodb://localhost:27017/ecommerce
The reason you are having the error:
It's simply because of the way you are writing the MongoDB URI in the .env file i.e MONGODB_URI="mongodb://localhost:27017/ecommerce";
The dotEnv package would parse the value for MONGODB_URI as mongodb://localhost:27017/ecommerce";, notice the double-quote(") and the semi-colon(;) at the end, they are not supposed to be there and that is what is causing the error.
The fix:
All you need to do is remove the semi-colon and everything should be fine: MONGODB_URI="mongodb://localhost:27017/ecommerce"
Though my rendering path is correct when I hit http://localhost:4444/admin/posts/create it shows some error like
Error: Failed to lookup view "/admin/posts/create" in views directory "D:\node practise\CMS\views"
app.js file is like
const express = require('express');
const app = express();
const path = require('path');
const exphbs = require('express-handlebars');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/cms', { useNewUrlParser: true })
.then(db => {
console.log('MONGO CONNECTED!');
})
.catch(error => {
console.log('MONGO NOT CONNECTED!');
})
//making app to use static file
app.use(express.static(path.join(__dirname, 'public')));
//define template engine
app.set('view engine', 'handlebars');
//set default engine
app.engine('handlebars', exphbs({defaultLayout: 'home'}));
//load routes
const home = require("./routes/home/index");
const admin = require("./routes/admin/index");
const posts = require("./routes/admin/posts");
//use routes
app.use(home);
app.use("/admin", admin);
app.use("/admin/posts", posts);
//setting up server
app.listen(4444, () => {
console.log('Listening....');
});
I have posts.js that handles this route like
const express = require("express");
const router = express.Router();
router.all('/*', (req, res, next) => {
req.app.locals.layout = 'admin';
next();
})
router.get('/', (req, res) => {
res.send('It works!');
})
router.get('/create', (req, res) => {
res.render('/admin/posts/create');
})
module.exports = router;
And I have my views folder structure as
What may be the cause of error? When I try to send response it works but when I try to render the view it shows error.
Can you try res.render('admin/posts/create');?
If the view folders is set properly like this: app.set('views', './views'), you should be able to resolve simple view name like res.render('myview') under ./views folder