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);
Related
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'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 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"
I just tried to create simple login and registration form with mongodb version 3.2.21 because I've got Windows 7 with 32bit CPU so here is the code
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var consolidate = require('consolidate');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var multer = require('multer')
var upp = multer()
var bodyParser = require('body-parser')
var router = express.Router()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(upp.array());
app.use(express.static('public'));
app.engine('html', consolidate.mustache);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
var mongoDB = 'mongodb://localhost/my_database';
mongoose.connect(mongoDB, {useNewUrlParser: true});
// Get Mongoose to use the global promise library
mongoose.Promise = global.Promise;
//Get the default connection
var db = mongoose.connection;
if(db){
console.log('connection')
}
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
var Schema = mongoose.Schema;
var SomeModelSchema = new Schema({
username: String,
password: String
});
var SomeModel = mongoose.model('SomeModel', SomeModelSchema );
var newuser = new SomeModel();
app.get('/', function(req, res){
res.render('mainpage')
})
app.get('/reg', function(req, res){
res.render('reg')
})
app.post('/reeg', function(req,res){
newuser.username = req.body.username;
newuser.password = req.body.password;
newuser.save(function (err, savedObject){
if (err){
console.log(err)
}else{
console.log(savedObject);
res.sendFile(__dirname + '\\views\\mainpage.html')
}})
});
app.post('/login', function(req,res){
var userr = req.body.usernamee
var pass = req.body.passwordd
newuser.findOne({username: userr, password: pass}).exec(),
function(err,obj){
if(err) {return res.status(404)
}else if(!obj){
res.send('notregistered')
}if(obj){
res.send('hey' + userr)
}
}})
http.listen('8080')
and this is giving me this error
So what is problem here? I am not using express router yet and this code is in one file
newuser is not a model, it's an instance of SomeModel - list of methods here
findOne is method of model - SomeModel list of methods here
so replace: newuser.findOne to SomeModel.findOne
I've rewritten overall code for better readability, async/await features, with object destructuring examples and etc best practices:
'use strict';
const path = require('path');
const http = require('http');
const express = require('express');
const socketIO = require('socket.io');
const bodyParser = require('body-parser');
const consolidate = require('consolidate');
// DB connection
const mongoose = require('mongoose');
const connectionString = 'mongodb://localhost/my_database';
mongoose.Promise = global.Promise;
mongoose
.connect(connectionString, {useNewUrlParser: true})
.then(() => {
console.log('Connection to database established');
})
.catch(error => {
console.error('MongoDB connection error:', error.message);
process.exit(-1);
});
// End of: DB connection
// Defining DB schemas and models
const Schema = mongoose.Schema;
const UserSchema = new Schema({
username: String,
password: String
});
const User = mongoose.model('User', UserSchema);
// End of: Defining DB schemas and models
// Initial app configuration
const app = express();
const server = http.Server(app);
const io = socketIO(server);
app.engine('html', consolidate.mustache);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('public'));
// End of: Initial app configuration
// App route handlers
app.get(
'/',
(req, res) => {
res.render('mainpage');
});
app.get(
'/reg',
(req, res) => {
res.render('reg');
});
app.post(
'/reg',
async (req, res) => {
try {
const {username, password} = req.body;
const user = await User.create({username, password});
console.log('Created user:', user);
res.sendFile(path.join(__dirname, 'views', 'mainpage.html'));
}
catch (error) {
res.status(500).send(error.message);
}
});
app.post(
'/login',
async (req, res) => {
try {
const {username, password} = req.body;
const user = await User.findOne({username, password}).select('-password').lean();
if(!user) {
res.send('User: ' + username +' not registered');
return;
}
res.send('hey ' + username);
}
catch (error) {
res.status(500).send(error.message);
}
});
// End of: App route handlers
// Binding http listener to port
server.listen('8080');
Notice: lean is method of query manual here
Fix Your login form:
<form action="/login" method="POST">
<input type="text" placeholder="username" name="username">
<input type="password" placeholder="pass" name="password">
<button type="submit">Login</button> <br/>
or <strong>Sign Up</strong>
</form>
P.S. Write in comments if something will go wrong.
When I did res.json (newschema) on post action, the properties are not displayed any more on Postman and also in Mongodb.
This is formations.routes
const express = require('express');
const router = express.Router();
const Formation = require('../models/formations');
const mongoose = require('mongoose');
const config = require('../config/database');
router.get('/', function(req, res){
//Formation.getFormations(function(err, formations){
// if(err)throw err;
// res.json(formations);
//});
Formation.find({})
.exec(function(err, Formations){
if(err){
console.log('error');
}else{
res.json(Formations);
}
})
});
router.post('/', function(req, res){
console.log('post a formations');
var newFormation = new Formation();
newFormation.title = req.body.title;
newFormation.url = req.body.url;
newFormation.description = req.body.description;
newFormation.save(function(err, newFormation){
if(err){
console.log('error insertion');
} else {
res.json(newFormation);
//res.json({success: true, msg:'user registred'});
}
});
});
This is formation.models
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const config = require('../config/database');
const FormationSchema = mongoose.Schema ({
title: String,
url: String,
description: String
});
module.exports = mongoose.model('Formation', FormationSchema, 'Formations');
This is my app.js ( endpoint)
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const mongoose = require('mongoose');
const config = require('./config/database');
const User = require('./models/user');
const Formation = require('./models/formations');
mongoose.connect(config.database , { useNewUrlParser: true });
mongoose.connection.on('connected', () => {
console.log('connected to database... ' + config.database);
});
mongoose.connection.on('error', (err) => {
console.log('database error'+err);
});
/*mongoose.connect('mongodb://localhost:27017/hello', { useNewUrlParser: true });
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('we are connected!');
});*/
const app = express();
const users = require('./routes/users');
const formations = require('./routes/formations');
//port number
const port = 3001;
//cors middleware
app.use(cors({
origin: 'http://localhost:4200'
}));
//passwport middelware
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport); //pour implémenter fichier passport.js
//set static folder
app.use(express.static(path.join(__dirname + '/public')));
//BodyParser middleware
app.use(express.json());
app.use(bodyParser.json());
app.use('/users', users);//hedhiya ki nekteb /users barka f url yemchili direct lel const users = require('./routes/users'); fichier hedhka
app.use('/formations', formations);
//c un route
//just meloul 7atineha bch ntastiw beha
//index route
app.get('/', function(req, res){
res.send('invalid endpoint');
});
//start Server
app.use(bodyParser.urlencoded({extended:true}));
app.listen(port, () => {
console.log('Server started on port' +port);
});
And this is how I make a post action in Postman
The save method only has an error parameter in the callback. You are adding a newFormations parameter which will always be undefined and in the scope of the method you are returning undefined in the res.json call. To fix it remove the newFormation parameter as below:
newFormation.save(function(err){
if(err){
console.log('error insertion');
} else {
res.json(newFormation);
//res.json({success: true, msg:'user registred'});
}
});