Reputation: 138
This is my first post on StackOverflow :).
I have made a delete route in express to delete the user and his profile:
// @route DELETE api/profile/
// @desc Delete user and profile
// @access Private
router.delete(
'/',
passport.authenticate('jwt', { session: false }),
(req, res) => {
Profile.findOneAndDelete({ user: req.user.id })
.then(() => {
console.log(req.user.id);
User.findOne({_id: req.user.id }).then(user=>console.log(user));
User.findOneAndDelete({ _id: req.user.id });
})
.then(() => {
res.json({ success: true });
});
}
);
After I make the delete request from Postman with the user's token I get the success response, but when I check MongoDB, the profile is gone, but the user is still there.
The first noob idea I got was that the problem is because of the passport, that I'm not getting the right id back. I was wrong ofc, the profile was gone, and the 2 console.log's I added were returning the right user id and user:
5f6a380f874e5c2fe454ac10
{
_id: 5f6a380f874e5c2fe454ac10,
name: 'test Testeson',
email: '[email protected]',
password: '$2a$10$uiq7Q080gS/.4xEbF2W/cuXG2MgnacqObKTLezUyuHBI0qnFB1Dca',
date: 2020-09-22T17:44:47.254Z,
__v: 0
}
Then I thought it was a javascript async problem, I have stared at it for a very long time, and I don't see the problem, I even tried to refactor with await async and wrapped the whole callback function in an async wrapper. Which was unnecessary.
I even checked the MongoDB user's permissions, but it was ok, ofc, the profile was deleted... And the mongoose user schema is this:
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = User = mongoose.model('user', UserSchema);
Maybe it's a small noobish, stupid mistake, but I have been stuck for hours...
So any help would be greatly appreciated,
Thank you, :)
Upvotes: 1
Views: 739
Reputation: 1447
Try refactoring your code to use async/await instead and see if it works. You're probably chaining .then()
incorectly. I write something like this:
router.delete(
'/',
passport.authenticate('jwt', { session: false }),
async (req, res) => {
const { id } = req.user;
try {
await Profile.findOneAndDelete({ user: id });
await User.findOneAndDelete({ _id: id });
res.json({ message: "Success" });
} catch(e) {
res.sendStatus(500)
}
}
);
Let me know if this works for you.
Upvotes: 0
Reputation: 64
Try adding .then() block to findOneAndDelete() and see.
User.findOneAndDelete({ _id: req.user.id }).then();
For me also if then block was not there operation were not successful, after adding then block only the operations were successfully executing.
Upvotes: 1