I am very new to node JS and mongo.
I am working on a personal website that stores a user's information in my database.
For simplicity, let's say I have the following form in jade...
form(class="inputs", action="/login", method="post")
input(type="text", name="email",class="form-control", id="emailLogin", placeholder="Queen's Email")
I already set up a database, and I was able to connect to it using the following javascript...
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/user');
var db = mongoose.connection;
db.on('error', console.error);
db.once('open', function() {
// Create your schemas and models here.
});
I want to store the input from email for every user that registers using the form above.
I am guessing I would first have to create a schema, which would probably look like this, but I'm not sure...
var Schema = mongoose.Schema;
var userSchema = new Schema({
email: String
});
//I think I have to create a model too?
And to get POST data I think I would need some code that looks like this...
app.post('/login', function(request, response){
//I am not sure what to put inside
});
My question is, can someone show me how to implement all these together so that every time a user registers with their email, it is saved in the database. It is very hard to research this, and have tried and failed many times.
EDIT
Here is my index.js file...
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'QChat' });
});
module.exports = router;
Also, here is another file in my routes directory called users.js, I'm not sure what its purpose is...
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
Here are some sample codes, hope it could help you.
var userSchema = new Schema({
email: String
});
var User = mongoose.model('User', userSchema);
app.post('/login', function(request, response){
var u = new User({
email: request.body.name
});
u.save(function(err) {
if (err)
throw err;
else
console.log('save user successfully...');
});
});
Also to parse the post url correctly, express could be used here, sample codes as below.
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
user.model.js
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, Q = require('q')
;
var UserSchema = mongoose.Schema({
email: String,
})
UserSchema.methods.Save = function() {
return Q.ninvoke(this, 'save');
}
var User = mongoose.model('User', UserSchema);
user.controller.js
var mongoose = require('mongoose')
, User = mongoose.model('User')
;
app.post('/create', function(request, response){
var user = new User();
user.email = request.body.email;
return user.Save().then(function(users) {
// some code if save succeed
}, function(err){
// some code if save failed
});
});
Related
I'm working on a node.js app, and every time I run this code it pops up a reference error saying that Post is not defined. When I put the post route into app.js instead of submit.js, it works fine. That leads me to believe it's because submit.js doesn't "see" the model defined in app.js. I'm very new to web development, so it's probably something pretty basic that I'm missing.
app.js
var express = require('express');
var mongoose = require('mongoose');
var submitRouter = require('./routes/submit');
var app = express();
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/posts");
//Mongoose Schema
var postSchema = new mongoose.Schema({
username: String,
date: Date,
title: String,
link: String,
text: String,
votes: Number,
community: String
});
var Post = mongoose.model("Post", postSchema);
app.use('/submit', submitRouter);
module.exports = app;
submit.js
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
router.post('/', function(req, res, next){
var newPost = new Post(req.body);
newPost.save()
.then(item => {
res.json(newPost);
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
module.exports = router;
Post is not defined It’s because you don’t have mongoose schema defined in submit.js like you did in App.js.
You are creating an instance to Post using new Post but the Post doesn’t exist in submit.js
I would recommend you to put your schema in separate file and import it in submit.js
Create a folder called schema and inside this folder create a file name called PostSchema.js
PostSchema.js
var mongoose = require('mongoose');
//Mongoose Schema
var postSchema = new mongoose.Schema({
username: String,
date: Date,
title: String,
link: String,
text: String,
votes: Number,
community: String
});
var Post = mongoose.model("Post", postSchema);
module.exports = Post;
Import post schema in submit.js
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Post = require('./schema/PostSchema.js');
router.post('/', function(req, res, next){
var newPost = new Post(req.body);
newPost.save()
.then(item => {
res.json(newPost);
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
module.exports = router;
By the way, it’s not an issue with Express Router.
I'm having trouble figuring out how to save a json object from a third party api to my personal localhost mongodb. I believe I'm supposed to create another method within the api controller but am not sure what kind of method should be used any help would be great thanks!
Here is my code sorry if this is a dumb question.
//server.js
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var mongoose = require('mongoose');
var Router = require('./routes');
var morgan = require('morgan');
var port = process.env.PORT || 3000;
var app = express();
//database connect
mongoose.connect('mongodb://localhost/Emagispace')
app.use(
express.static('views'),
bodyParser.json(),
bodyParser.urlencoded({extended : true}),
morgan('dev')
);
Router(app);
app.listen(port, ()=>{
console.log(`Server running on ${port}`);
//Routes
var API = require('./controllers/api');
module.exports = (app)=>{
app.get('/', (req, res)=>{
res.sendFile('index.html', {root : './views'});
});
app.get('/api/emagispace', API.product)
}
//API controller
var request = require('request-promise');
var baseURI = 'example';
module.exports = {
product : (req, res)=>{
request({
method : 'GET',
url : `${baseURI}/api/emagispace/${req.query.products}`
})
.then((resp)=>{
console.log('Product list : ', resp);
res.send(resp).save();
})
}
}
In order use mongoose for saving the documents you'll need to specify the Schema first.
//product-model.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ProductSchema = new Schema({
name: String,
price: String,
//And all other data you need
});
var Product = mongoose.model('Product', ProductSchema);
Also you can do validation and much else. Please see the docs.
Then you can use .insertMany to save them in one shot or iterrate over your documents:
var Product = require('../models/product-model.js');
...
.then((resp)=>{
//I assume that resp is an array of products here
console.log('Product list : ', resp);
//Go over your product list and save them
for (var product of resp) {
var p = new Product(product);
p.save();
}
//OR
Product.insertMany(resp);
res.send(resp);
})
After this you'll have products collection in your local db.
Also you can warp these calls into a method if you want.
I'm trying to learn the MEAN stack by following this tutorial and I have run into an error. Unfortunately, I can't spot out where I went wrong exactly.
I was trying to test routes out in Postman by creating a user but I kept getting back 'Cannot POST /users'.
Can anyone help me out here? Thanks in advance!
routes.js
// Dependencies
var mongoose = require('mongoose');
var User = require('./model.js');
// Opens App Routes
module.exports = function(app) {
// GET Routes
// --------------------------------------------------------
// Retrieve records for all users in the db
app.get('/users', function(req, res){
// Uses Mongoose schema to run the search (empty conditions)
var query = User.find({});
query.exec(function(err, users){
if(err)
res.send(err);
// If no errors are found, it responds with a JSON of all users
res.json(users);
});
});
// POST Routes
// --------------------------------------------------------
// Provides method for saving new users in the db
app.post('/users', function(req, res){
// Creates a new User based on the Mongoose schema and the post bo.dy
var newuser = new User(req.body);
// New User is saved in the db.
newuser.save(function(err){
if(err)
res.send(err);
// If no errors are found, it responds with a JSON of the new user
res.json(req.body);
});
});
};
model.js
// Pulls Mongoose dependency for creating schemas
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// Creates a User Schema. Defines how user data is stored to db
var UserSchema = new Schema({
username : {type: String, required: true},
gender : {type: String, required: true},
age : {type: Number, required: true},
favlang : {type: String, required: true},
location : {type: [Number], required: true}, //[Long, Lat]
htmlverified : String,
created_at : {type: Date, default: Date.now},
updated_at : {type: Date, default: Date.now}
});
// Sets the created_at parameter equal to the current time
UserSchema.pre('save', function(next){
now = new Date();
this.updated_at = now;
if(!this.created_at){
this.created_at = now
}
next();
});
// Indexes this schema in 2dsphere format (critical for running proximity searches)
UserSchema.index({location: '2dsphere'});
// Exports the UserSchema for use elsewhere. Sets the MongoDB collection to be used as:
module.exports = mongoose.model('scotch-user', UserSchema);
server.js
// Dependencies
// -----------------------------------------------------
var express = require('express');
var mongoose = require('mongoose');
var port = process.env.PORT || 3000;
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var app = express();
// Express Configuration
// -----------------------------------------------------
// Sets the connection to MongoDB
mongoose.connect("mongodb://localhost/MeanMapApp");
// Logging and Parsing
app.use(express.static(__dirname + '/public')); // sets the static files location to public
app.use('/bower_components', express.static(__dirname + '/bower_components')); // Use BowerComponents
app.use(morgan('dev')); // log with Morgan
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.urlencoded({extended: true})); // parse application/x-www-form-urlencoded
app.use(bodyParser.text()); // allows bodyParser to look at raw text
app.use(bodyParser.json({ type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json
app.use(methodOverride());
// Routes
// ------------------------------------------------------
require('./app/routes.js')(app);
// Listen
// -------------------------------------------------------
app.listen(port);
console.log('App listening on port ' + port);
I believe this is where your error is.
Instead of:
module.exports = mongoose.model('scotch-user', UserSchema);
Try:
module.exports = mongoose.model('User', UserSchema);
Also, look into using Express.js for your routes. When you are testing on Postman, double check that you are entering all "required" parts for your MongoDB Schema.
I just copied your scripts and I have no problems at all!
Make sure you're using the right methods and routes in postman.
Small tip: Mongoose handles it own schema's, so there is no need to export them.
You can easily do the following
app.js
// Dependencies
// -----------------------------------------------------
var express = require('express');
var mongoose = require('mongoose');
var port = process.env.PORT || 3000;
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var app = express();
// Load all models
require('./app/model');
// Express Configuration
model.js
// remove module.exports in the last line
mongoose.model('User', UserSchema);
routes.js
// Dependencies
var mongoose = require('mongoose');
var User = mongoose.model('User');
I have this very simple code that stores superhero name and power to database.
All connections work normally. When i ran mongod i used --dbpath C:/nodeprojects/sankarit/data. I have tried change the path like 50 times with different paths.
So my code sends nimi and supervoima (name, superpower) from client side and it tries to add them to database but literally nothing happens in db. When i write console.log("yay it works") on save function, it says that its working. And if i console log superhero it seems to work normally.
Here is client side:
$http.post("api/juttu", {nimi: "besthero", supervoima: "whiskey"}).success(function(response){
console.log(response.data);
}).error(function(){
console.log("Error")
})
Here is my server.js:
var express = require('express');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.set('debug', true);
// SANKARI SCHEMA
var Sankari = require('./app/models/sankarit');
// CONTROLLERIT
var testCtrl = require('./server/testCtrl');
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.use('/public', express.static(__dirname + '/public'));
// DB conn
// I have tried with /test, /heros, /sankariKanta, /sankarit
mongoose.connect('mongodb://127.0.0.1:27017/test');
mongoose.connection.once('connected', function() {
console.log("Connected to database")
});
//PORTTI
var port = process.env.PORT || 8080;
// ROUTER
var router = express.Router();
app.get('/', function(req, res) {
res.sendFile('index.html', {root: __dirname});
});
app.post("/api/juttu", testCtrl.juttu);
app.listen(port);
Here is the testCtrl:
var Sankari = require("../app/models/sankarit");
module.exports.juttu = function (req, res){
// Tried also var uusiSankari = new Sankari(req.body);
var uusiSankari = new Sankari();
uusiSankari.nimi = req.body.nimi;
uusiSankari.supervoima = req.body.supervoima;
uusiSankari.save(function(err){
if(err){
console.log(err);
} else{
// This is always showing up
console.log("This is working!");
}
});
};
Also when i try console.log(req.body); It is working correctly.
Here is schema(sankarit.js):
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SankariSchema = ({
nimi: String,
supervoima: String
});
module.exports = mongoose.model('Sankari', SankariSchema);
When i run the program, the mongoose debug thing says:
Mongoose: sankaris.insert({ __v: 0, _id: ObjectId("57ff0a649dbf169c15000001"), nimi: 'besthero', s
upervoima: 'whiskey' }) {}
So when i debug and console log everything the program does it seems to work like dream. I have made these MEAN stack tutorials like 5-10 and everytime database worked normally. This is first time i'm trying to make whole code by myself. I tried solve this whole night but i didn't get absolutely anywhere.
You forgot to use the Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SankariSchema = Schema({
nimi: String,
supervoima: String
});
module.exports = mongoose.model('Sankari', SankariSchema);
I don't know what I am doing wrong and need some help please. I keep getting the same error. I log the doc it keeps saying undefined help please been trying to fix this for 16hours straight.
my model: discussionmodel.js
var mongoose = require('mongoose');
// Discussion Schema
var DscSchema = mongoose.Schema({
dsc: String,
discussionID: String
});
// Discussion model
Dsc = mongoose.model('Discussion', DscSchema);
module.exports = Dsc;
my route: questions.js
var express = require('express');
var router = express.Router();
require('../models/discussionsmodel.js');
router.get('/:id', function(req, res, next) {
var id = req.params.id;
Dsc.findById(id, function(err, doc){
console.log("log doc " + doc);
res.render('questions.ejs', {docs: doc});
});
});
module.exports = router;
My view: questions.ejs (just a part of the f
<h1>Q&A app</h1>
<h2>Discussion: <%= docs.dsc %></h2>
<h2>Questions</h2>