I'm trying to build my first MEAN Stack application and I'm using postman to check my insertion in my DB and I get a message that says "user created!", but after checking the DB in MongoLab. I do not get any document inserted in the collections. here's my code:
Here's my repo in case you need it: https://github.com/pevargasg/joberistyNode
app.js
var express = require('express')
var app = express()
var morgan = require('morgan');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
//My one modules
var User = require('./app/models/user');
var Company = require('./app/models/company');
//Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(morgan('dev'));
//Connection to DB
//mongoose.Promise = global.Promise;
//Feel free to use your own mongoLab link below for testing purposes
mongoose.connect('mongodb://user:password#dsXXXXXX.mlab.com:19768/jobersity',function(err){
if(err){
console.log("Not connection to DB" + err);
throw err;
}
else{
console.log("Connected to DB");
}
});
//Routes
/*app.get('/', function (req, res) {
res.send('Hello World!')
})*/
//Creating Users
app.post('/users',function(req,res){
//res.send('test');
var user = new User();
user.username = req.body.username;
user.password = req.body.password;
user.email = req.body.email;
/*user.firstName = req.body.firstName;
user.lastName = req.body.lastName;
user.major = req.body.major;*/
//Save user
user.save();
res.send('user created!');
});
user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//Table for usersSchema
var UserSchema = new Schema({
username:{type: String, lowercase: true, required: true, unique: true},
password:{type: String, required: true},
email:{type: String, lowercase: true, required: true, unique: true},
/*firstName: {type: String, required: true},
lastName: {type: String, required: true},
major: {type: String, required: true},
jobsApplied:[{
title: String,
description: String,
position: String
}]*/
});
module.exports = mongoose.model('User', UserSchema);
Your code works successfully when I run it.
Two things I did notice:
Your package.json file includes mongojs when it doesn't seem to get used. The mongooose package will pull the mongodb dependency it need when you call npm install.
Your connection string is included in clear text in your repository. Try to get in the habit of importing any sensitive information into your app through a config file.
For example, create a config file, e.g. ./config/db.js:
module.exports = {
'uri' : 'mongodb://user:pwd#host1:port1/dbname'
}
Then import the file into your app:
var dbConfig = require('./config/db.js');
The variable can then be used be used in your code:
mongoose.connect( dbConfig.uri, function(err){ ... } )
Finally, add this file (./config/db.js) to your .gitignore.
Related
Currently I have integrated successfully to routes, request and config.
Application Structure
app.js - The entry point to our application. This file defines our express server and connects it to MongoDB using mongoose. It also requires the routes and models we'll be using in the application.
config/ - This folder contains configuration for passport as well as a central location for configuration/environment variables.
routes/ - This folder contains the route definitions for our API.
models/ - This folder contains the schema definitions for our Mongoose models.
routes/api/users.js
var mongoose = require('mongoose');
var router = require('express').Router();
var passport = require('passport');
var User = mongoose.model('User');
var auth = require('../auth');
router.post('/users', function(req, res, next){
var user = new User();
user.username = req.body.user.username;
user.email = req.body.user.email;
user.setPassword(req.body.user.password);
user.save(req, res).then(function(){
return res.json({user: user.toAuthJSON()});
}).catch(next);
});
module.exports = router;
models/User.js
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var crypto = require('crypto');
var jwt = require('jsonwebtoken');
var secret = require('../config').secret;
var UserSchema = new mongoose.Schema({
username: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/^[a-zA-Z0-9]+$/, 'is invalid'], index: true},
email: {type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/\S+#\S+\.\S+/, 'is invalid'], index: true},
bio: String,
image: String,
favorites: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Article' }],
following: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
hash: String,
salt: String
}, {timestamps: true});
/**<<HERE>> Does not work inside the models. <<HERE>>**/
UserSchema.plugin(uniqueValidator, {message: i18n.__('user.register.errors.is_already_taken')});
mongoose.model('User', UserSchema);
app.js
var http = require('http'),
path = require('path'),
methods = require('methods'),
express = require('express'),
bodyParser = require('body-parser'),
session = require('express-session'),
cors = require('cors'),
passport = require('passport'),
errorhandler = require('errorhandler'),
mongoose = require('mongoose');
cookieParser = require('cookie-parser');
i18n = require('i18n');
var isProduction = process.env.NODE_ENV === 'production';
// Create global app object
var app = express();
app.use(cors());
app.use(cookieParser())
// Configure i18n
i18n.configure({
locales:['en', 'es'],
directory: __dirname + '/locales',
objectNotation: true,
//defaultLocale: 'en',
register: global,
cookie: 'lang'
})
i18n.init();
// you will need to use cookieParser to expose cookies to req.cookies
app.use(cookieParser());
// i18n init parses req for language headers, cookies, etc.
app.use(i18n.init);
// Support "Accept-Language" : "es" or "en" via headers
app.use(function (req, res, next) {
i18n.init(req, res);
if (typeof req.locale !== 'undefined') {
console.log('locale : ', req.locale);
i18n.setLocale(req.locale);
}else{
var locale = i18n.getLocale();
res.set('Content-Language', locale);
}
next();
});
// finally, let's start our server...
var server = app.listen( process.env.PORT || 3000, function(){
console.log('Listening on port ' + server.address().port);
});
But when I try translate inside a models/ for example i18n.__('my-key'), this does not detect the locale so this returns the locale for default "en", but from header i receive correctly the lang "es".
Please let me know how I will fix it :)
I am following a YouTube tutorial from Jose Annunziato. I created my server.js and did all the required settings and configurations for my database connection. Now when I am posting something from the form to the server: it shows the data is sent to the server successfully but when I go to the mongo console to verify if the data is received and database is created or not. I run db it says test I run show dbs and there I can't see my new Database. I am not sure what the actual problem is because I did everything Jose said in the tutorial.
Server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/blogfall2016');
var PostSchema = mongoose.Schema({
title: {type: String, required: true},
body: String,
tag: {type: String, enum:['POLITICS', 'ECONOMY', 'EDUCATION']},
posted: {type: Date, default: Date.now},
});
var PostModel = mongoose.model('PostModel', PostSchema)
// GET /style.css etc
app.use(express.static(__dirname + '/public'));
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/api/blogpost", CreatePost);
function CreatePost(req, res) {
var post = req.body;
console.log(post);
PostModel.create(post);
res.json(post);
}
app.listen(3000);
If your schema and data you want to insert are matched then it should work.
Try below code. instead of PostModel.create(post);
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/nnnnnn', function (err) {
if (!err) {
console.log('connection successful');
} else {
console.log(err)
}
});
var PostSchema = mongoose.Schema({
title: { type: String, required: true },
body: String,
tag: { type: String, enum: ['POLITICS', 'ECONOMY', 'EDUCATION'] },
posted: { type: Date, default: Date.now },
});
var PostModel = mongoose.model('PostModel', PostSchema)
// GET /style.css etc
app.use(express.static(__dirname + '/public'));
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/api/blogpost", CreatePost);
function CreatePost(req, res) {
var post = req.body;
console.log(post);
// static data
var post = {
title: 'asdfasdf',
body: 'asdfasdfasdfasdf',
tag: 'POLITICS',
posted: new Date()
}
var postModel = new PostModel(post);
postModel.save(function (err, data) {
if (err) {
console.log('Error', err);
} else {
console.log('data inserted');
}
});
res.json(post);
}
app.listen(3000);
Instead of below line
mongoose.connect('mongodb://localhost/blogfall2016');
Try this one to make sure that database created successfully first,
then do your operation
mongoose.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
I am learning about Mongoose. I am working along this tutorial and running into a stumbling block with adding entries to my database, run through Heroku MongoDB. I am able to add to the existing collection "test1" when I load the app 'trywithmongodb' but I in my Heroku mLab console I do not see anything added to any collections when I access the page "trywithmongoose". Help? Here is the relevant code for in index.js:
var express = require('express');
var mongoose = require("mongoose");
var mongo = require('mongodb').MongoClient;
app.get("/trywithmongodb", function(request,response){
response.send("Looking at the /trywithmongodb page");
var configDB = require('./config/database.js');
//add to the database
mongo.connect(configDB.url , function(err, db) {
var shorturl = db.collection("test1");
var date = new Date();
var newsitejson={original_url: "accessed at", site_number: date.getHours()+":"+date.getMinutes()}
shorturl.insert(newsitejson)
db.close()
})
});
app.get('/trywithmongoose', function (request, response) {
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
// grab the user model
var User = require('./app/models/user');
// create a new user
var newUser = User({
name: 'Peter ',
username: 'peter45',
password: 'willbehashed',
admin: true
});
// save the user
newUser.save(function(err) {
if (err) throw err;
console.log('User created!');
});
response.send("You are looking at /trywithmongoose");
});
And here's the full file user.js for the schema:
// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a schema
var userSchema = new Schema({
name: String,
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
admin: Boolean
});
// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', userSchema);
// make this available to our users in our Node applications
module.exports = User;
What am I missing? The Mongoose docs say that mongoose.plugin() registers a plugin for all schemas. This is not working. I CAN register my plugin on EACH schema.
My plugin:
module.exports = function (schema, options) {
schema.set('toObject',{
transform: function (doc, ret, options) {
return {
test: 'It worked!'
};
}
});
};
My schema:
var testPlugin = require('test-plugin.js');
var personSchema = mongoose.Schema({
_id : { type: String, default: $.uuid.init },
ssn : { type: String, required: true, trim: true },
first : { type: String, required: true, trim: true },
middle : { type: String, required: true, trim: true },
last : { type: String, required: true, trim: true }
});
personSchema.plugin(testPlugin);
var model = mongoose.model('Person', personSchema);
module.exports = model;
The code above works, unfortunately. However, the following code does not:
var personSchema = mongoose.Schema({
_id : { type: String, default: $.uuid.init },
ssn : { type: String, required: true, trim: true },
first : { type: String, required: true, trim: true },
middle : { type: String, required: true, trim: true },
last : { type: String, required: true, trim: true }
});
var model = mongoose.model('Person', personSchema);
module.exports = model;
My test app:
var testPlugin = require('test-plugin.js');
mongoose.plugin(testPlugin);
mongoose.Promise = global.Promise;
mongoose.connect(config.db);
mongoose.connection.on('error', function (err) {
if (err) { throw err; }
});
mongoose.connection.once('open', function (err) {
if (err) { throw err; }
seeds.doSeed(function(err){
if (err) { return process.exit(1); }
models.Person.find({}, function(err, people){
if (err) { throw err; }
var person = people[0];
var oPerson = person.toObject();
console.log(JSON.stringify(oPerson));
});
});
});
I've tried moving the mongoose.plugin(testPlugin) all over the app.js file... after the connect, etc... and nothing has worked.
Plugins might not be registered with mongoose.plugin(myMongoosePlugin) because mongoose models were created before you are registering plugins globally.
In case if you have expressjs routes:
Make sure that in your app.js (server.js) you are registering mongoose plugins before you are registering/creating expressjs routes (which are using mongoose models to communicate with database).
Example:
in app.js
const express = require(express);
const mongoose = require('mongoose');
const myMongoosePlugin = require('<Mongoose Plugin file path>');
mongoose.plugin(myMongoosePlugin);
let app = express();
//register expressjs routes
require('<Express routes file path>')(app, express.Router());
// or create expressjs routes
app.post('/person', (req, res, next) => {
//where someMethod is using person mongoose model
this.someController.someMethod(someArguments)
.then((user) => {
res.json(user);
}).catch((error) => {
next(error);
});
});
// ... Some other code ...
mongoose.connect(<databaseConnectionString>);
app.listen(<Port>);
Try requiring your model also in your app.js file. Somewhere after mongoose.plugin(testPlugin).
This is not the best solution but work , you must define your Schema in each file and then export that
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({ ... })
module.exports = UserSchema;
and then you should implement just one file for setup your models , for example
const mongoose = require('mongoose');
// import all of your schemas
const userSchema = require(./user/modelSchema);
const TicketSchema = require(./Ticket/modelSchema);
// *** implement your (Global Plugin) here ***
mongoose.plugin(myPlugin);
// define and create all of your models
const User = mongoose.model('User', userSchema);
const Ticket = mongoose.model('Ticket', TicketSchema);
module.exports = {
userModle: User,
ticketModel: Ticket,
}
This is just another view of what #Andrei Surzhan already stated.
The key here is to Apply the plugins before the Routes.
I recently got this issue, where the plugin's didn't work on a Global scale but it did when added them individually on the creation of their Schema.
For reference, my project is structured this way.
// server.js file
require('dotenv').config();
const http = require('http');
const mongoose = require('mongoose');
const myPlugin = require('path-to-my-plugin');
mongoose.plugin(myPlugin);
const app = require('./app');
const PORT = process.env.PORT || 8000;
const server = http.createServer(app);
// MONGO CONNECTION
mongoose.connect(process.env.MONGODB_URI);
mongoose.connection.on('open', () => console.log('MongoDB connection ready!'));
mongoose.connection.on('error', console.error);
server.listen(PORT, console.log(`Listening on PORT ${PORT}`));
// app.js file
const express = require('express');
// Routes
const clientsRouter = require('./routes/clients/clients.router');
const paymentsRouter = require('./routes/payments/payments.router');
const app = express();
// Parse incoming requests with JSON payloads
app.use(express.json());
// Parse incoming requests with Form payloads
app.use(
express.urlencoded({
extended: false,
})
);
app.use('/clients', clientsRouter);
app.use('/payments', paymentsRouter);
module.exports = app;
As you can see at server.js we add the plugin before even importing app.js this is because when we import app.js we will call the routes and the plugin will not be passed.
Another way to do it, is adding the plugin on each Schema.
Example
// clients.model.js
const mongoose = require('mongoose');
const myPlugin = require('path-to-my-plugin');
const clientSchema = new mongoose.Schema({ ... });
clientSchema.plugin(myPlugin);
module.exports = mongoose.model('Client', clientSchema);
The issue that it doesnt let me use the genre schema
i have 2 schemas user and genre
user schema works fine but the genre schema is undefind
user.js - schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Genre = require('../Models/genre');
// create a schema
var userSchema = new Schema({
name: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
age: String,
gender: String,
genres: [Genre.genreSchema]
});
// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', userSchema);
// make this available to our users in our Node applications
module.exports = User;
genre.js - schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a schema
var genreSchema = new Schema({
name: { type: String, required: true, unique: true },
age: String,
gender: String
});
// the schema is useless so far
// we need to create a model using it
var Genre = mongoose.model('Genre', genreSchema);
// make this available to our genres in our Node applications
module.exports = Genre;
genre controller - router --- same as user router controller
var express = require('express');
var bodyParser = require('body-parser');
var Genre = require('../Models/genre');
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
// middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
next(); // make sure we go to the next routes and don't stop here
});
router.route('/genres')
// create a genre
.post(function(req, res) {
console.log(Genre);
**//here is the error when trying to post new genre**
var Genre = new Genre(req.body); // create a new instance of the user model
// save the genre and check for errors
Genre.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Genre created!' });
});
})
// get all the genres
.get(function(req, res) {
Genre.find(function(err, genres) {
if (err)
res.send(err);
res.json(genres);
});
});
module.exports = router;
server.js - the app js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var userRouter = require('./Controllers/user');
var genreRouter = require('./Controllers/genre');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017'); // connect to our datababase
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', userRouter);
app.use('/api', genreRouter);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('see whats happening on port ' + port);
why the model is undefind only when i post new genre? and for user it works fine?
is it the way to do schema whithin schema? or there is a better way?
i have try to use only the genre model with out the user and it still same error
i hope i am clear enough
thanks for the helpers
You shouldn't be using the same name for the schema and for the new Genre.
try changing it to
var newGenre = new Genre(req.body); // create a new instance of the user model
// save the genre and check for errors
newGre.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Genre created!' });
});