Reputation: 335
I'm trying to delete both .files and .chunk data but all the posts that I have found are either outdated or do not apply to my issue.
This is my backend route:
const mongoose = require("mongoose");
const config = require("config");
const db = config.get("mongoURI");
let gfs;
const conn = mongoose.createConnection(db);
conn.once("open", () => {
gfs = new mongoose.mongo.GridFSBucket(conn.db, {
bucketName: "photos"
});
});
router.delete('/:imageID', async (req, res) => {
gfs.delete({_id: req.params.imageID, root:"photos"}, function(error){
test.equal(error, null);
}
Any ideas?
Upvotes: 2
Views: 3415
Reputation: 335
Solved! to succesfully delete GridFS .files and .chunks just find the obj_id and do gfs.delete( obj_id)
Code:
router.delete("/:imageID", auth, async (req, res) => {
try {
const post = await Post.findOne({ image: req.params.imageID });
console.log(post);
if (post.user != req.user.id) {
res.status(401).send("Invalid credentials");
}
// Here:
const obj_id = new mongoose.Types.ObjectId(req.params.imageID);
gfs.delete( obj_id );
await post.remove();
res.json("successfully deleted image!");
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
});
Upvotes: 7