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' });
});
router.post('/login', function(req, res) {
console.log("processing");
res.send('respond with a resource');
});
module.exports = router;
And here is the code I am using to stored POST data into my mongoDB database. This is located in my app.js file...
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/user');
var db = mongoose.connection;
var Schema = mongoose.Schema;
db.on('error', console.error);
db.once('open', function() {
console.log("connected");
var Schema = new mongoose.Schema({
mail : String
});
var User = mongoose.model('emp', Schema);
app.post('/login', function(request, response){
console.log("here");
new User({
mail: request.body.email
}).save(function(err, doc) {
if (err)
res.json(err);
else
console.log('save user successfully...');
});
});
Code works fine up until it reaches the app.post, after that it does not seem to read the rest of the code.
I know my index.js file works because when I submit the form, I get to a page that displays respond with a resource (because of the send function). But for some reason, app.post is not being read, am I missing something?
Here is my jade html to show that I am implementing everything correctly...
form(class="inputs", action="/login", method="post")
input(type="text", name="email",class="form-control", id="emailLogin", placeholder="Queen's Email")
input(type="submit",name = "homePage" class ="loginButton" value="Log In" id="loginButton")
Please try to move the following code out of db.once('open')
db.on('error', console.error);
db.once('open', function() {});
app.post('/login', function(request, response){
console.log("here");
new User({
mail: request.body.email
}).save(function(err, doc) {
if (err)
res.json(err);
else
console.log('save user successfully...');
});
});
Another issue in your code, please make sure the first parameter of mongoose.model is User, otherwise, one error could pop up.
var UserSchema = new mongoose.Schema({
mail : String
});
var User = mongoose.model('User', UserSchema);
Related
Guys I'm going through a udemy class on Node and Express and I've gotten stuck. I'm implementing a route using a GET method ruest. The route has the form of "campgrounds/:id" however, there's a route above that has the name of "/campgrounds/new" which is submission form. here's the link to working web app.
and the webpage of working app
http://webdevcamp-miatech.c9users.io/campgrounds
when you click on any of the buttons "more info" it will redirect to "campgrounds/:id" for now I"m just testing the route and I'm printing some text.
app.js file
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose");
//connect mongoose db
mongoose.connect("mongodb://localhost/yelp_camp");
app.use(bodyParser.urlencoded({extended: true})); //parsing html request
app.set("view engine", "ejs"); //handling vies through ejs pages
//schema/model for data to be inserted in db
var campgroundSchema = new mongoose.Schema({
name: String,
image: String,
description: String
})
var Campground = mongoose.model("Campground", campgroundSchema);
Campground.create({
name: "Salmon Creek",
image: "https://farm6.staticflickr.com/5786/20607281024_5c7b3635cc.jpg",
description: "This is a huge granite hill, no bathroom campground"
}, function(err, campground) {
if(err) {
console.log(err);
}
else {
console.log("Created Campground");
console.log(campground);
}
})
//default route
app.get("/", function(req, res) {
res.render("landing");
})
app.get("/campgrounds", function(req, res) {
Campground.find({}, function(err, allCampgrounds) {
if(err) {
console.log(err);
}
else {
res.render("campgrounds", {campgrounds: allCampgrounds});
}
})
});
//method to add to database and redirect to campgrounds
app.post("/campgrounds", function(req, res) {
// res.send("you hit post route");
//get data from form and add to campgrounds array
var name = req.body.name;
var imgUrl = req.body.image;
var newCampGround = {name: name, image: imgUrl};
//adding to database table
Campground.create(newCampGround, function(err, newlyCreated) {
if(err) {
console.log(err);
}
else {
res.redirect("/campgrounds");
console.log(newlyCreated);
}
});
});
app.get("/campgrounds/new", function(req, res) {
res.render("new.ejs");
})
//displaying especific campground
app.get("campgrounds/:id", function(req, res) {
//find campground with id
// Campground.FindById(req.param)
// res.render("single.ejs");
res.send("This will be the single page!");
})
//starting server
app.listen(process.env.PORT, process.env.IP, function() {
console.log("server started!..");
});
Here's my project on c9.io
https://ide.c9.io/miatech/webdevcamp
missing slash before campgrounds
app.get("/campgrounds/:id", function(req, res) {
//find campground with id
// Campground.FindById(req.param)
// res.render("single.ejs");
res.send("This will be the single page!");
})
I get `TypeError: Cannot set property 'auto' of null when i try to update my mongodb using angularjs on the frnt end and nodejs on the backend. Here is my code :
my angular code:
scope.lol.then(function(user){
console.log(user[0]._id);
iden=user[0]._id;
$scope.userss = user;
console.log(iden);
$http.put('/api/updateUser', user[0]);
});
And my api :
module.exports.updateUser = function (req, res) {
var id = req.param.id;
User.findById(id, function(err, user) {
if (err) throw err;
// change the users location
user.auto = 'true';
// save the user
user.save(function(err) {
if (err) throw err;
console.log('User successfully updated!');
});
});
}
$http.put('/api/updateUser', user[0]);
change to
$http.put('/api/updateUser', {params:{id:user[0]._id}});
and on api
var id = req.param.id;
change to
var id = req.query.id;
I'm going to assume that you're using ExpressJS for your API, so you'll need to use body-parser to retrieve the body of your request. You can read more about it here: http://expressjs.com/en/api.html - ctrl+f for body-parser to skip to the good bits :)
Try something like this in your API (you'll probably need to tweak it to fit your app, but it shows you how to pull stuff out of the body of the request. There are code examples on the link I posted too):
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(express.json());
app.use(express.urlencoded());
app.listen(1337);
app.put('/updateUser', updateUser);
function updateUser (req, res) {
var id = req.body.id;
User.findById(id, function(err, user) {
if (err) throw err;
// change the users location
user.auto = 'true';
// save the user
user.save(function(err) {
if (err) throw err;
console.log('User successfully updated!');
});
});
}
Hope that helps!
I made this node js app and then i tried with postman but every time i made a request that involves mongodb, it keeps loading. The function find of the model is where the code stops and the callback is never called.
app.js
var express = require("express"),
app = express(),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
mongoose = require('mongoose');
//Connection to DB
mongoose.connect('mongodb://localhost:27017/users', function(err, res) {
if(err) {
console.log('ERROR: connecting to Database. ' + err);
}
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
var models = require('./models/user')(app, mongoose);
var userContoller = require('./controllers/user');
var router = express.Router();
router.get('/', function(req, res) {
console.log('GET');
res.send("Hello World!");
});
app.use(router);
var users = express.Router();
users.route('/users')
.get(userContoller.findAllUsers);
app.use('/api', users);
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
models/user.js
exports = module.exports = function(app, mongoose){
var userSchema = new mongoose.Schema({
userName: { type: String },
password: { type: Number }
});
mongoose.model('User', userSchema);
};
controllers/user.js
var mongoose = require('mongoose');
var User = mongoose.model('User');
//GET - Return all tvshows in the DB
exports.findAllUsers = function(req, res) {
console.log('llega');
User.find(function(err, users) {
if(err) res.send(500, err.message);
console.log('GET /users')
res.status(200).jsonp(users);
});
};
The mongodb server is started through the console but i don't know how to check it.
Thanks!
EDIT:
I made the code easier for me to test and solve the problem.
The code now is this and im not getting the connection to mongodb.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', function() {
console.log('error');
});
db.once('open', function() {
console.log('connected');
});
I don't get in the console the error or the connected.
In the mongod console i get some messages saying that a new connection was made. This happens every time i open the nodejs program.
Thanks
I think the problem is that you are giving call back to the mongoose.connect function. In my case i did:
mongoose.connect(url, options)
const db = mongoose.connection
db.on('error', function () { console.log('Cannot Connect to DB') })
db.once('open', function () { console.log('Mongoose Connected to DB') })
Also instead of:
users.route('/users').get(userContoller.findAllUsers);
You may try:
users.get('/users', userController.findAllUsers);
And I realized that you don't pass a next argument to your controller which express generally complains if you dont pass.
Edit: I think i found the error.
When you are using the .find function you need to pass 2 arguments. In your case because you are not passing the callback as the second argument it never gets called.
User.find({}, callback) should do it.
I found the problem.
The version of mongoose was older than the needed to connect to my mongodb version. Just update it via npm and good to go.
Am getting the following error MissingSchemaError: Schema hasn't been registered for model "Post". while i have defined the model.
Here is the code where i use the schema :
var express = require('express');
var router = express.Router();
var mongoose = require( 'mongoose' );
var Post = mongoose.model('Post');
//Used for routes that must be authenticated.
function isAuthenticated (req, res, next) {
// if user is authenticated in the session, call the next() to call the next request handler
// Passport adds this method to request object. A middleware is allowed to add properties to
// request and response objects
//allow all get request methods
if(req.method === "GET"){
return next();
}
if (req.isAuthenticated()){
return next();
}
// if the user is not authenticated then redirect him to the login page
return res.redirect('/#login');
};
//Register the authentication middleware
router.use('/posts', isAuthenticated);
router.route('/posts')
//creates a new post
.post(function(req, res){
var post = new Post();
post.text = req.body.text;
post.created_by = req.body.created_by;
post.save(function(err, post) {
if (err){
return res.send(500, err);
}
return res.json(post);
});
})
//gets all posts
.get(function(req, res){
console.log('debug1');
Post.find(function(err, posts){
console.log('debug2');
if(err){
return res.send(500, err);
}
return res.send(200,posts);
});
});
//post-specific commands. likely won't be used
router.route('/posts/:id')
//gets specified post
.get(function(req, res){
Post.findById(req.params.id, function(err, post){
if(err)
res.send(err);
res.json(post);
});
})
//updates specified post
.put(function(req, res){
Post.findById(req.params.id, function(err, post){
if(err)
res.send(err);
post.created_by = req.body.created_by;
post.text = req.body.text;
post.save(function(err, post){
if(err)
res.send(err);
res.json(post);
});
});
})
//deletes the post
.delete(function(req, res) {
Post.remove({
_id: req.params.id
}, function(err) {
if (err)
res.send(err);
res.json("deleted :(");
});
});
module.exports = router;
And here is the code where i define the schema :
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var postSchema = new mongoose.Schema({
username: { type: Schema.ObjectId, ref: 'User' }, //should be changed to ObjectId, ref "User"
created_at: {type: Date, default: Date.now},
text: String
});
var userSchema = new mongoose.Schema({
username: String,
password: String, //hash created from password
created_at: {type: Date, default: Date.now}
})
mongoose.model('Post', postSchema);
mongoose.model('User', userSchema);
Can anyone help me ?
I've got an error while i try to auth via vkontakte (vk.com) (passport-vkontakte)
Error: ReferenceError: User is not defined
Here is my auth.js
var express = require('express');
var passport = require('passport'), VKontakteStrategy = require('passport-vkontakte').Strategy;
var router = express.Router();
var app = express();
router.get('/', function(req, res) {
res.send('Auth');
});
passport.use(new VKontakteStrategy({
clientID: 000, // VK.com docs call it 'API ID'
clientSecret: '***',
callbackURL: "http://127.0.0.1:3000/auth/vkontakte/callback"
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate({ vkontakteId: profile.id }, function (err, user) {
return done(err, user);
});
}
));
router.get('/vkontakte',
passport.authenticate('vkontakte'),
function(req, res){
// The request will be redirected to vk.com for authentication, so
// this function will not be called.
});
router.get('/vkontakte/callback',
passport.authenticate('vkontakte', { failureRedirect: '/' }),
function(req, res) {
// Successful authentication, redirect home.
var User = req.User;
res.redirect('/');
});
router.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
module.exports = router;
Express ver: 4
Define User Model
Mongoose or Mongoskin Example
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_database');
var Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
var BlogPost = new Schema({
author : ObjectId
, title : String
, body : String
, date : Date
});
var Post = mongoose.model('ModelName', BlogPost);
Post.findOrCreate({ id: QUERY }, function (err, docs) {
});
You need to create a model so your strategy can interact with your application properly. In your case, this model will be for users so it is appropriately named User as an entity.
Boilerplate Code to Get You Started
This code was added from the strategy developers to get you started.
User.findOrCreate({ vkontakteId: profile.id }, function (err, user) {
return done(err, user);
});
It's the same concept, hope this clears things up.