Im working on a function where there is page asking user for a profile picture and some info.
so far thats what i have
router.post('/edit/:id', async function(req, res) {
let user
const id = req.params.id
try{
user = await User.findById(id)
user.firstname= req.user.firstname,
user.lastname= req.user.lastname,
user.religion= req.user.religion,
user.education= req.user.education,
user.language= req.user.language,
user.lookingfor=req.body.lookingfor,
user.preferEdu=req.user.preferEdu,
user.preferReligion= req.user.preferReligion,
user.bio= req.user.bio
if (req.file != null && req.file !== '') {
await upload(req, res, (err) => {
if(err){
console.log(err)
} else {
if(req.file == undefined){
console.log('no file')
} else {
console.log(req.file)
User.findByIdAndUpdate({_id: id}, {$set: {
imageurl: req.file.location
}}, {new: true}, (err, result) => {
res.redirect('/dashboard')
})
}
}
})
}
} catch{
if (user != null) {
console.log ('no user')
} else {
res.redirect('/dashboard')
}
}
})
the page just jump back to '/dashboard' without anything being saved
before i have a function that just handle upload images, and it was sucessful
router.post('/edit/:id', function(req, res) {
const id = req.params.id
upload(req, res, (err) => {
if(err){
console.log(err)
} else {
if(req.file == undefined){
console.log('no file')
} else {
console.log(req.file)
User.findByIdAndUpdate({_id: id}, {$set: {
imageurl: req.file.location
}}, {new: true}, (err, result) => {
res.redirect('/dashboard')
})
}
}
});
});
I can see the image was uploaded to amazon s3 and req.file.location was logged in the console. but it was not saved in my mongo database.
any help will be appreciated! thanks
you have to use capital letter of 'l' of location. You should switch the line req.file.location to req.file.Location. S3 return json with keys having a captial letter as initials.
Hope, this helps! let me know if that works!
Related
I have this problem in this part of my code
the curse that I study with there is no problem with the teacher I also search a lot
on this code is the controller of the API that I try to build
exports.create = (req, res, next) => {
upload(req, res, function (err) {
if (err) {
next(err)
}
else {
const path = req.file != undefined ? req.file.path.replace(/\\/g, '/') : "";
var model = {
categoryName: req.body.categoryName,
categoryDescription: req.body.categoryDescription,
categoryImage: path != "" ? '/' + path : ''
}
categoriesService.createCatergry(model, (error, results) => {
if (error) {
return next(error)
}
else {
return res.status(200).send({
message: 'Success',
data: results
})
}
})
}
})
}
that the code in service file
async function createCategory(parmas, callback) {
if (!parmas.categoryName) {
return callback({
massage: 'Category name is required'
},
""
);
}
const model = new category(parmas);
model.save().then((response) => {
return callback(null, response);
}).catch((error) => {
return callback(error);
})
}
when I click on it say remove unsend function
Please check if it's not misspelled createCatergry
app.get("/users/:id", function (req, res) {
User.findById(req.params.id, function (err, foundUser) {
if (err) {
console.log(err)
} else {
console.log(foundUser)
}
})
Item.countDocuments({ UID: req.params.id }, function (err, itemCount) {
if (err) {
console.log(err)
} else {
console.log(itemCount)
}
})
Item.find({ UID: req.params.id }, function (err, foundItems) {
if (err) {
console.log(err)
} else {
console.log(foundItems)
}
})
res.render("users/show", { user: foundUser, newListItems: foundItems, itemCount: itemCount})
For some reason this wont render and keeps saying that the variables dont exist despite the callbacks above. Using EJS for render.
I may be reading the code incorrectly, but aren't the callback variables out of scope for the res.render method?
You may need to return the callbacks from each of the Mongoose queries and store them in variables that are within the scope of the res.render method.
As suggested by Richie, you cannot access the variables from.inside the callbacks in the outer scope
app.get("/users/:id", function (req, res) {
User.findById(req.params.id, function (err, foundUser) {
if (err) { console.log(err) }
else {
console.log(foundUser)
Item.countDocuments({ UID: req.params.id }, function (err, itemCount) {
if (err) { console.log(err) }
else {
console.log(itemCount)
Item.find({ UID: req.params.id }, function (err, foundItems){
if (err) { console.log(err) }
else {
console.log(foundItems);
res.render("users/show", { user: foundUser, newListItems: foundItems, itemCount: itemCount})
}
});
}
});
}
});
});
Notice that I've put the res.render method inside the callbacks so that the variables are available to it.
EDIT
As suggested by Marcel Djaman, You should probably use async/await to make code more readable. Read more about async/await here
app.get("/users/:id", async function (req, res) {
try {
const foundUser = await User.findById(req.params.id);
console.log(foundUser)
const itemCount = await Item.countDocuments({ UID: req.params.id });
console.log(itemCount)
const foundItems = await Item.find({ UID: req.params.id });
console.log(foundItems);
res.render("users/show", { user: foundUser, newListItems: foundItems, itemCount: itemCount});
} catch(err) {
console.error(err)
}
});
You can notice how much simpler this code is than the one above it.
I was troubleshooting why my route wasn't working and i came across this.
In my ./routes/jobs.js,
router.delete("/:id", (req, res) => {
Job.findByIdAndDelete(req.params.id, (err, job) => {
if (!err) {
res.json({ msg: "job deleted"});
} else {
console.log(err);
}
});
});
When i tested on postman, Delete - http://localhost:5000/dashboard/60b9405e1ea
Would return the id only 60b9405e1ea and not delete the db job.
I changed my route to "/" and tested it out. using http://localhost:5000/dashboard in postman.
router.delete("/", (req, res) => {
Job.findByIdAndDelete(req.params.id, (err, job) => {
if (!err) {
res.json({ msg: "job deleted"});
} else {
console.log(err);
}
});
It executed the delete request with {msg: "job deleted"}. (Obviously didnt delete db job since no id was given).
Keep in mind in my server.js im using,
app.use("/dashboard", require("./routes/jobs"));
Any help would be appreciated on why /:id is not being executed
As you are getting the id in the console, it's the problem with the query you make.
Try any of these,
Model.remove({ _id: req.body.id }, function(err) {
if (!err) {
message.type = 'notification!';
}
else {
message.type = 'error';
}
});
or
Model.findOneAndRemove({id: req.params.id}, function(err){
});
or a traditional approach:
Model.findById(id, function (err, doc) {
if (err) {
// handle error
}
doc.remove(callback); //Removes the document
})
Im using POSTMAN to delete contact using id and it returns
{
"n": 0,
"ok": 1
}
This is my delete code so far
router.delete('/contact/:id', (req, res, next) => {
contact.remove({ _id: new objectId(req.params._id) }, function(err, result) {
if (err) {
res.json(err);
} else {
res.json(result);
}
});
});
You need to pass the _id value as an ObjectID, not a string:
var mongodb = require('mongodb');
router.delete('/contact/:id', (req, res, next) => {
contact.deleteOne({ _id: new mongodb.ObjectID(req.params._id) }, function(err, result) {
if (err) {
res.json(err);
} else {
res.json(result);
}
});
});
id !== _id
change :id in your route to :_id and you should be fine.
I cannot remove an element inside of an array that is a property of a MongoDB Model.
Please remember this is a NodeJS module mongooseJS and not the real MongoDB so functionalities are not the same..
GOAL: Delete an object from the statusLiked array. | I have also confirmed that the value of status.id is correct.
Model:
Const userSchema = new mongoose.Schema({
myStatus: Array,
statusLiked: Array,
)};
Delete:
1. Deletes the status(works). 2. Delete the status from User.statusLiked(no work).
exports.deleteStatus = (req, res, next) => {
var CurrentPost = req.body.statusid; // sends in the status.id
Status.remove({ _id: CurrentPost }, (err) => {
if (err) { return next(err); }
// vvvv this vvv
User.update( {id: req.user.id}, { $pullAll: {_id: CurrentPost }, function(err) { console.log('error: '+err) } });
req.flash('success', { msg: 'Status deleted.' });
res.redirect('/');
});
};
What happens: The specific status(object) is deleted from the database. But the status still remains in the User.statusLiked array.
What I want to happen: Status to be deleted from the User.statusLiked array and the status to be deleted from the database. Then, reload the page and display a notification.
I got it to work somehow. Working code:
exports.deleteStatus = (req, res, next) => {
var CurrUser = req.body.userid;
var CurrentPost = req.body.post;
Status.remove({ _id: CurrentPost }, (err) => {
if (err) { return next(err); }
console.log('meeee'+CurrentPost+'user: ' +CurrUser);
req.flash('success', { msg: 'Status deleted.' });
res.redirect('/');
});
User.update(
{ _id: new ObjectId(CurrUser)},
{ $pull: { myStatus : { _id : new ObjectId(CurrentPost) } } },
{ safe: true },
function (err, obj) {
console.log(err || obj);
});
};