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"
Related
I am simply trying to render a user to ejs file. Before i render data from database
here is the code
const express = require('express')
const app = express()
const path = require('path')
const ejs = require('ejs')
app.set('view engine','ejs')
var MongoClient = require('mongodb').MongoClient;
const mongoose = require('mongoose')
const messageSchema = {
name:String,
message:String
}
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static("views"));
app.get('/',(req,res)=>{
res.render(path.join(__dirname,'views','index.ejs'))
})
app.get('/form',(req,res)=>{
res.render(path.join(__dirname,'views','form.ejs'))
})
app.use(express.urlencoded({ extended:false }))
const Message = mongoose.model('Message',messageSchema)
app.post('/form',function(req,res){
let newMessage = new Message({
name:req.body.name,
message:req.body.message
})
console.log(newMessage)
newMessage.save()
res.redirect('/')
})
app.get('/form',(req,res) => {
res.render('form', { user:"FILIP"})
})
app.listen(3000)
Problem is i get an error that user is not defined.I wathced tutorials and watched trough forums and everybody has the same syntax as me . I dont know where problem might be. If you could help me i would be glad.
Not sure why this is happenening, tried removing all instances of new, switching to let from const ect. Can run site however when I run a post request via a html form, get an error on the line "const user = new UserSchema" ect. of TypeError: UserSchema is not a constructor.
const express = require('express');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bodyParser = require('body-parser');
let app = express();
let mongoDB = //hiding url for obvious reasons
mongoose.connect(mongoDB, { useNewUrlParser: true });
mongoose.Promise = global.Promise;
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
const UserSchema = new Schema({
name: String,
email: String
});
app.set('view engine', 'ejs');
app.use('/assets', express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function(req,res){
res.render('landingPage');
});
app.post('/', function (req, res) {
const user = new UserSchema(req.body.name, req.body.email);
user.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
app.listen(3000);
You have to assign the schema as a mongoose model.
var User= mongoose.model('user', UserSchema);
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...
i can't find the solution.please help..
MongooseError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string.
if (process.env.NODE_ENV !== 'production') {
require('dotenv').load()
}
const express = require('express')
const app = express()
const expressLayouts = require('express-ejs-layouts')
const bodyParser = require('body-parser')
const methodOverride = require('method-override')
const indexRouter = require('./routes/index')
const authorRouter = require('./routes/authors')
const bookRouter = require('./routes/books')
app.set('view engine', 'ejs')
app.set('views', __dirname + '/views')
app.set('layout', 'layouts/layout')
app.use(expressLayouts)
app.use(methodOverride('_method'))
app.use(express.static('public'))
app.use(bodyParser.urlencoded({ limit: '10mb', extended: false }))
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.use('/books', bookRouter)
app.listen(process.env.PORT || 3000)
Create the .env file on your root project. Then under that file copy-paste this line i.e
DATABASE_URL="192.168.1.1:3000"
then on main server file may be app.js or server.js or somethingelse.js file before the line i.e const mongoose = require('mongoose') copy-paste this line
require('dotenv').config();
and then console.log(process.env.DATABASE_URL)// This will return your Database URL
Hope you understand the concept.
I'm using the Wes Boss Node.js tutorial and have been encountering a number of issues with schema errors.
My database is currently running on mLab and MongoDB Compass. It was fine yesterday when I left for work, and I had just added my first bit of data to the DB successfully. This morning I go to continue where I left off, and everything is suddenly broken.
I've tried deleting the node_modules directory, running npm cache clean, and npm install. I have tried changing the order of the dependencies. I thought it might be that the connection just needed restarted, so I closed the connection, exited Compass, re-opened and re-connected to the DB. I tried deleting the "sessions" table and re-connecting. No such luck.
I've tried plugging the database's server address into my browser's URL bar and I receive a message indicating that the connection was successful.
Error:
MissingSchemaError: Schema hasn't been registered for model "Store". Use mongoose.model(name, schema)
at MissingSchemaError (C:\Users\Misha\Desktop\dang-thats-delicious\node_modules\mongoose\lib\error\missingSchema.js:20:11)
app.js:
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');
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(cookieParser());
app.use(session({
secret: process.env.SECRET,
key: process.env.KEY,
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next) => {
res.locals.h = helpers;
res.locals.flashes = req.flash();
res.locals.user = req.user || null;
res.locals.currentPath = req.path;
next();
});
app.use((req, res, next) => {
req.login = promisify(req.login, req);
next();
});
app.use('/', routes);
app.use(errorHandlers.notFound);
app.use(errorHandlers.flashValidationErrors);
if (app.get('env') === 'development') {
app.use(errorHandlers.developmentErrors);
}
app.use(errorHandlers.productionErrors);
module.exports = app;
index.js:
const express = require('express');
const router = express.Router();
const storeController = require('../controllers/storeController');
const { catchErrors } = require('../handlers/errorHandlers');
router.get('/', storeController.homePage);
router.get('/add', storeController.addStore);
router.post('/add', catchErrors(storeController.createStore));
module.exports = router;
start.js:
require('./models/Store');
const mongoose = require('mongoose');
const Store = mongoose.model('Store');
require('dotenv').config({ path: 'variables.env' });
mongoose.connect(process.env.DATABASE);
mongoose.Promise = global.Promise;
mongoose.connection.on('error', (err) => {
console.error(`${err.message}`);
});
require('./models/Store');
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}`);
});
Well, I think I solved my own problem. My storeController.js file needed require('../models/Store'); at the top, right below const mongoose = require('mongoose');
However, now I'm getting another error, and I believe it's related to removing my stored sessions from the DB:
express-session deprecated req.secret; provide secret option at app.js:38:9
Going to attempt to re-create the DB and see what happens.