I got a 500 error and de description says: Mongoose is not defined when i call /delPost, but in the same file "post.js" the functions /addPost and /getPosts are working and use mongoose.model without problems. im a newbie and have searched a lot but can't fix that issue, hope you can help me.
routes/post.js
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
POST message to board (WORKING)
router.post('/addPost', function(req, res) {
if(req.body){
var post = mongoose.model('post');
var newpost = new post(req.body);
console.log(newpost);
newpost.save(function(err, newpost){
if(err) return res.send(200,{msg: 'not saved'});
})
console.log('save ok');
}
else{
res.send(200,{msg: 'no data received'});
}
});
GET messages from DB to show in HTML (WORKING)
router.get('/getPosts', function(req, res) {
var post = mongoose.model('post');
post.find(function(err, posts){
if(err) return console.log(err);
// console.log(posts);
res.send(posts);
})
});
DELETE a post (NOT WORKING)
router.post('/delPost/:rel', function(req, res){
// var mongoose = require('mongoose');
var post = moongose.model('post');
post.remove({_id: req.params.rel},function(err) {
if(err) return handleError(err);
console.log(err);
})
});
AJAX Call to /delPost route
function delPost(event){
event.preventDefault();
console.log('delpost');
var confirmation = confirm('Are you sure to delete this message?');
if(confirmation === true){
$.ajax({
type:'POST',
url: '/post/delPost/' + $(this).attr('rel')
}).done(function(response){
console.log('delete done.. ');
}).fail(function(response){
console.log('delete failed');
})
}
};
Related
I have a little problem to understand that how to solve this error.i am just a beginner to nodejs and mongodb/mongoose.I am creating a component in reactjs to update any particular documents using its user_id which i am passing a params in routes.
there is the code:
const express = require('express');
const mongoose = require('mongoose');
const mongodb = require('mongodb')
const user = require('../schema');
const router = express.Router();
router.get('/:id', function (req, res) {
const userid = {
userid: (req.params.id || '')
}
console.log('getting to be updated data');
user.db1.findOne(userid, function (err, data) {
if (err) throw err
res.send(data)
console.log(data)
});
});
module.exports = router
//here is the user model:
const userSchema = new mongoose.Schema({
userid:{type:String},
fullname:{type:String},
phone:{type:Number},
email:{type:String},
})
const skillSchema = new mongoose.Schema({
userid:{type:Number},
skills:{type:String},
})
const users = mongoose.model('users',userSchema);
const skills = mongoose.model('skills',skillSchema);
module.exports ={
db1 : users,
db2 : skills
}
I guess you haven't specified in the find.one () function by which parameter it will search. Try it by typing your own column name instead of id.
user.db1.findOne({ id: userid } ,function(err, data){
if (err) throw err
res.send(data)
console.log(data)
});
Or you can change your function and use findById().
user.db1.findById(userid, ,function(err, data){
if (err) throw err
res.send(data)
console.log(data)
});
I need to find the events of a user but I can't retrieve the user since I can't pass the user id to route file of events.
app.js :
var Router = express.Router();
Router.use("/users/:uid/events", events);
events.js :
Router.post("/",function (req,res) {
User.findOne({
_id:req.params.uid
},function (err, foundUser) {
if(err){
res.json({success:false, message:"The user couldn't be found"});
}else{
console.log(req.params.uid);
console.log(foundUser);
var event = new Event();
event.title = req.body.title;
event.description = req.body.description;
event.save(function (err) {
if(err){
console.log(err);
}
});
foundUser.events.push(event);
}
})
});
As a result :
uid = undefined
foundUser = null
How can i pass uid parameter to the events.js?
I think this should work.
app.js:
var Router = express.Router();
Router.use("/users/", events);
events.js:
Router.post("/:uid/events", function (req,res) {
User.findOne({
_id:req.params.uid
},function (err, foundUser) {
if(err){
res.json({success:false, message:"The user couldn't be found"});
}else{
console.log(req.params.uid);
console.log(foundUser);
var event = new Event();
event.title = req.body.title;
event.description = req.body.description;
event.save(function (err) {
if(err){
console.log(err);
}
});
foundUser.events.push(event);
}
});
});
While Lazyexpert's answer is a way to solve this problem, I found what I have been exactly looking for today.
In order to pass uid from app.js
Router.use("/users/:uid/events", events);
to another route make sure that your router contains {mergeParams:true}
var express = require('express');
var Router = express.Router({mergeParams:true});
JS:
var express = require('express');
var router = express.Router();
// Mongoose
var mongoose = require('mongoose');
var mongoosedb = 'DBURL';
mongoose.connect(mongoosedb);
var database = mongoose.connection;
database.on('error', console.error.bind(console, 'connection error:'));
database.once('open', function() {
console.log('Mongoose is connected.');
});
var taskSchema = mongoose.Schema({
name: String,
isDone: Boolean
});
var Tasks = mongoose.model('Tasks', taskSchema);
// Get all tasks
router.get('/tasks', function(req, res, next) {
Tasks.find(function(err, tasks) {
if(err) {
console.log('error');
res.send(err);
}
res.json(tasks);
});
});
// Get single task
router.get('/task/:id', function(req, res, next) {
Tasks.findOne({_id: mongojs.ObjectId(req.params.id)}, function(err, task) {
if(err) {
res.send(err);
}
res.json(task);
});
});
// Save task
router.post('/task', function(req, res, next) {
var task = req.body;
if(!task.title || !(task.isDone + '')) {
res.status(400);
res.json({
"error": "Bad Data"
});
} else {
task.save(function(err, task) {
if(err) {
res.send(err);
}
res.json(task);
})
}
});
// Delete task
router.delete('/task/:id', function(req, res, next) {
Tasks.remove({_id: mongojs.ObjectId(req.params.id)}, function(err, task) {
if(err) {
res.send(err);
}
res.json(task);
});
});
// Update task
router.put('/task/:id', function(req, res, next) {
var task = req.body;
var updTask = {};
if (task.isDone) {
updTask.isDone = task.isDone;
}
if (task.title) {
updTask.title = task.title;
}
if (!updTask) {
res.status(400);
res.json({
"error": "Bad Data"
});
} else {
task.update({_id: mongojs.ObjectId(req.params.id)}, updTask, {}, function(err, task) {
if(err) {
res.send(err);
}
res.json(task);
});
}
});
module.exports = router;
I'm simply just trying to add a record to MongoDB using Mongoose.
After some Googling I couldn't find answer. My .find and .findOne methods work fine but for some reason I get the error task.save is not a function. What am I doing wrong?
I think your task creation is being done incorrectly.
First go ahead and import your model up at the top with your dependencies so we can access the model methods directly:
var express = require('express');
var router = express.Router();
// Mongoose
var mongoose = require('mongoose');
var mongoosedb = 'DBURL';
var Task = require('mongoose').model('Task'); // add your Task model
Then, in your save a task code, change it to this:
// Save task
router.post('/task', function(req, res, next) {
var task = new Task(req.body) // See http://mongoosejs.com homepage demo example for basic creation
if(!task.title || !(task.isDone + '')) {
res.status(400);
res.json({
"error": "Bad Data"
});
} else {
task.save(function(err, task) {
if(err) {
res.send(err);
}
res.json(task);
})
}
});
As your current Task creation is setup, you're just setting it to the req.body contents but not actually initializing an instance via the mongoose methods.
I personally like to use mongoose promises instead, just because I tend to like the style more. But you could also do something like this, if you have given access to your Task model via grabbing it as a dependency (as shown above):
Task.create(req.body)
.then(function(newTask) {
console.log("Task created successfully.");
return res.json(newTask); // using res.json here
})
.catch(function(err) {
console.log("There was a problem creating task.");
return res.status(500).json(err); // sends status with json obj
})
Anyhow, I hope this helps, let me know if this works, if not I'll check back later and see!
Your variable task is the body object you have defined previously :
var task = req.body;
If you want to generate a Tasks document from it, use :
var newTask = new Tasks(task);
newTask.save(function(err, task) {
if (err) {
res.send(err);
}
res.json(task);
});
Check mongoose Models documentation
You have also confused task.update with Tasks.update
I'm a beginner at NodeJS / MongoDB so maybe it would be easy for you.
I have this simple code :
var MongoClient = require('mongodb').MongoClient;
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird')
MongoClient.connect("mongodb://localhost:27017/db_ldap_users", function(err, db) {
if(err) {
throw err;
}
console.log("connected to the mongoDB !");
});
var usersSchema = new mongoose.Schema({uid : String });
var Users = mongoose.model('Users', usersSchema);
app.get("/test", function(req, res) {
console.log("Service /test called");
var users = new Users();
users.uid = "James";
console.log("User created");
users.save(function(err) {
console.log("Callback");
if (err) {
console.log("error");
throw err;
}
console.log('added !');
res.send("ok");
});
});
Here is the output :
connected to the mongoDB !
Service /test called
User created
The problem is the user is never add to the DB. I have never entered in the callback, I don't know why, I have followed multiple tutorial and it seems to always works for them. Does someone has an idea ?
EDIT : I forget to add
mongoose.connect("mongodb://localhost:27017/db_ldap_users");
I was thinking the connection to the Database was enough Thanks
Thanks you
look this:
var mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/db_ldap_users");
var usersSchema = new mongoose.Schema({uid : String });
var Users = mongoose.model('Users', usersSchema);
app.get("/test", function(req, res) {
console.log("Service /test called");
var users = new Users();
users.uid = "James";
console.log("User created");
users.save(function(err) {
console.log("Callback");
if (err) {
console.log("error");
throw err;
}
console.log('added !');
res.send("ok");
});
});
I am using Mongoose and Express.js .
My Post request looks like this :
$('#update').on('click', function() {
var uname = $('#username').val();
var name = $('#name').val();
var json = {
user_name: name,
user_username: uname,
};
$.post("/saveprofile", json, function(data, error, xhr) {
if(!err)
window.location.href = "/feed";
});
});
This is how I'm handling the request :
app.post('/saveprofile', isLoggedIn, function(req, res) {
var username = req.body.user_username;
var uname = req.body.user_name;
User.findOne({$or:[{"facebook.email":req.user.facebook.email},{"local.email":req.user.local.email}]}, function (err, user){
user.name = uname;
user.username=username;
user.save();
res.send({redirect: '/feed'});
})
});
My documents get added into the db successfully but what I want is, when that happens it should redirect to a new page /feed . The above snippets mention 2 methods I've tried. But I've got no result . It doesn't redirect !
Edit:
Testing with exception handling gives undefined
app.post('/saveprofile', isLoggedIn, function(req, res) {
var username = req.body.user_username;
var uname = req.body.user_name;
try{
User.findOne({$or:[{"facebook.email":req.user.facebook.email},{"local.email":req.user.local.email}]}, function (err, user){
user.name = uname;
user.username=username;
user.save();
res.redirect("http://stackoverflow.com")
});
}
catch(ex){
console.log(ex) ;
}
});
Edit 2 :
I tried a sample request ...even it doesn't seem to redirect !
app.post('/test', isLoggedIn, function(req,res){
res.redirect("http://www.stackoverflow.com")
})
You can't make a redirection after an AJAX. You need to do it with Javascript.
So here is how we can do it,
Post request :
$('#update').on('click', function() {
var uname = $('#username').val();
var name = $('#name').val();
var json = {
user_name: name,
user_username: uname,
};
$.post("/saveprofile", json, function(data, err, xhr) {
if(!err)
window.location.href = data.redirect;
});
});
Server
app.post('/saveprofile', isLoggedIn, function(req, res) {
var username = req.body.user_username;
var uname = req.body.user_name;
User.findOne({$or:[{"facebook.email":req.user.facebook.email},{"local.email":req.user.local.email}]}, function (err, user){
user.name = uname;
user.username=username;
user.save(function(err){
if(!err)
res.send({redirect: '/feed'});
});
})
});
Link to Original Answer
Try res.redirect() instead :
res.redirect("/feed");