MongoDB Gridfs-stream 只删除文件而不删除块
我正在尝试从 MongoDB 数据库中删除文件和块,但我的路线仅删除文件而不是块。我已经看到了一些针对此问题的 StackOverflow 解决方案,但它们要么已经过时,要么基于已弃用的 remove()
函数。我看到另一个解决方案声称将 root:bucketName
添加到删除查询选项可以解决此问题,但它不适合我。
const router = require("express").Router();
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ObjectId = require("mongodb").ObjectId;
const { authUser } = require("../middleware/auth");
const uploadMulter = require("../middleware/upload");
const Grid = require("gridfs-stream");
const connection = mongoose.connection;
let gfs, gridfsBucket;
connection.once("open", () => {
gfs = Grid(connection.db, mongoose.mongo);
});
router.delete("/files/:_id", (req, res) => {
gfs
.collection("profilePictures")
.deleteOne({ _id: ObjectId(req.params._id) }, (err) => {});//only deletes the profilePicture.file, but not profilePicture.chunk
});
I am trying to delete a file and chunk from my MongoDB database but my route only deletes the file but not the chunk. I've seen a few StackOverflow solutions to this issue but they are either now outdated or are based on the deprecated remove()
function. I saw another solution that claimed that adding root: bucketName
to the delete query options fixes this issue, but it didn't for me.
const router = require("express").Router();
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ObjectId = require("mongodb").ObjectId;
const { authUser } = require("../middleware/auth");
const uploadMulter = require("../middleware/upload");
const Grid = require("gridfs-stream");
const connection = mongoose.connection;
let gfs, gridfsBucket;
connection.once("open", () => {
gfs = Grid(connection.db, mongoose.mongo);
});
router.delete("/files/:_id", (req, res) => {
gfs
.collection("profilePictures")
.deleteOne({ _id: ObjectId(req.params._id) }, (err) => {});//only deletes the profilePicture.file, but not profilePicture.chunk
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我发现使用
delete()
会删除块和文件,但它必须在 gridfsBucket。 StackOverflow 上的所有其他“解决方案”都使用gfs
上已弃用的remove()
或deleteOne()
。此解决方案的问题是
delete()
函数仅适用于BSON _id
,因此如果您想根据文件名或元数据删除文件,那么它就不起作用。I found that using
delete()
removes both the chunk and file but it must be ran on the gridfsBucket. All other "solutions" on StackOverflow use either the deprecatedremove()
ordeleteOne()
ongfs
.The issue with this solution is that the
delete()
function only works withBSON _id's
so If you would like to delete files based on filename or metadata then It wont work.