首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么不能删除带有ObjectId的gfs.files?

为什么不能删除带有ObjectId的gfs.files?
EN

Stack Overflow用户
提问于 2016-10-13 08:04:21
回答 2查看 1.6K关注 0票数 1

这已经让我困扰了一整天。我可以使用gfs.exist()找到带有_id的实际文件,但是当我运行到下一行代码时,每次都会得到一个错误,mongoose连接崩溃。这看起来很简单,但到目前为止还没有起到任何作用。

我的代码:

代码语言:javascript
复制
/**
 * Created by foolishklown on 10/2/2016.
 */

var Grid = require('gridfs-stream'),
    User = require('../../models/user'),
    mongoose = require('mongoose');


module.exports = function(id, ref, type, res) {
    console.log(ref.green);
    Grid.mongo = mongoose.mongo;

    var conn = mongoose.createConnection('mongodb://localhost/media');
    conn.once('open', function () {
        var gfs = Grid(conn.db);
        gfs.exist({_id: ref}, function(err, found) {
            if(err) {
                console.error('error finding file'.red);
            } else {
                console.info('found file', found);
                gfs.files.remove({_id: ref  }, function(err) {
                    if(err) {
                        console.error('error removing that file');
                        process.exit(1);
                    } else {
                        console.info('removed file: ', found.green);
                        deleteFromUserDb(id, type, ref);
                        res.status(200).send({id: id, type: type, ref: ref});
                    }
                });
            }
        });
    });
    conn.close();

    function deleteFromUserDb(userId, fileType, refId) {
        var userConn = mongoose.createConnection('mongodb://localhost/mean-auth', (error) => {
            if(error) {
                console.error('Error connecting to the mean-auth instance'.red);
                process.exit(1);
            } else {
                User.findById(userId, (err, doc) => {
                    if(err) {
                        console.error('Error finding user with id: ', uid);
                        process.exit(1);
                    } else {
                        console.log('original doc: ', doc);
                        doc.removeMedia(fileType, refId);
                        doc.save();
                        console.log('new doc: ', doc);
                    }
                })
            }
        });
    }
};

我尝试使用gfs.files.remove({_id: ref},function(.....) )无济于事

我也尝试过使用gfs.files.remove({_id: ref},{_id: 1},function(....) )

我也尝试过在不使用gfs.files.remove的情况下使用gfs.remove()来执行上述两种操作。

它一定是简单的东西,但它让我苦恼了一整天……谢谢

新编辑10/15..........我现在尝试只使用原生mongodb驱动程序。我可以找到包含字符串的文件,并将其转换为objectId。看起来操作完成没有问题,但当我使用shell查看文件是否已被删除时,它在fs.files和fs.chunks中仍然存在。这个真要了我的命!

代码语言:javascript
复制
deleteFile: function(userId, fileType, objId, res) {
        var ObjectId = require('mongodb');
        var client = mongodb.MongoClient;
        var _id = new ObjectId(objId);


        client.connect(mediaUri, (err, db) => {
            assert.equal(null, err);
            db.collection('fs.files').find({_id: _id}, (err, doc) => {
                if(err) {
                    console.error('error finding that document in files collection'.red);
                } else {
                    console.info('found the document: ', doc);
                    console.info('the document type is: ', typeof(doc));
                }
            });
            db.collection('fs.chunks').find({_id: _id   }, (err, doc) => {
                if(err) {
                    console.error('error finding that document in the chunks collection'.red);
                } else {
                    console.info('found the document(s): ', doc);
                    console.info('the document type is: ', typeof(doc));
                }
            });

            db.collection('fs.files').deleteOne({_id: _id}, (err, doc) => {
                console.log('document returned for deletion is: ', doc);
            });
            db.collection('fs.chunks').deleteOne({_id: _id}, (err, doc) => {
                console.log('documents deleted: ', doc);
                res.status(200).send({id: userId, type: fileType, ref: objId});
            });
            db.close();
        })
    }
EN

回答 2

Stack Overflow用户

发布于 2016-10-17 09:55:47

我做了错误的转换,使用了错误的方法。在为mongodb.ObjectiD()而不是mongodb.ObjectID()使用了一个新的构造函数之后,我取得了一些成功,另外我还调用了一些错误的方法。我查阅了文档,把事情理顺了。

我的CRUD操作的最终代码是:

代码语言:javascript
复制
/**
 * Created by foolishklown on 10/13/2016.
 */
var assert = require('assert'),
    path = require('path'),
    Grid = require('gridfs-stream'),
    fs = require('fs'),
    mongodb = require('mongodb'),
    mongoose = require('mongoose'),
    User = require('../../models/user'),
    mediaUri = 'mongodb://localhost/media',
    userUri = 'mongodb://localhost/mean-auth';

module.exports = {


    writeFile: function (file, userId, fileType, fileInfo, res) {
        var fileId;
        var fileTitle = file.originalFilename;
        var conn = mongoose.createConnection('mongodb://localhost/media', (error) => {
            if (error) {
                console.error('Error connecting to mongod media instance'.red);
                process.exit(1);
            } else {
                console.info('Connected successfully to mongod media instance in the write file!'.blue);
            }
        });
        // The following line is designating a file to grab/read, and save into mongo
        //  in our case it will be something from ng-file-upload that the user wants to upload
        var myFile = file.path;

        // Connect gridFs and mongo
        Grid.mongo = mongoose.mongo;

        conn.once('open', function () {
            console.log('connection open, ready for I/O!');
            var gfs = Grid(conn.db);

            // This write stream is how well write to mongo
            var writeStream = gfs.createWriteStream({
                // Name the file the way you want it stored in mongo
                filename: file.originalFilename,
                type: fileType,
                info: fileInfo
            });

            // Create a read stream, so that we can read its data, and then with that well use the
            //  write stream to write to the DB via piping the writestream
            var readStream = fs.createReadStream(myFile)
                .on('end', () => {
                    writeToUserDb(userId, fileType, readStream.id, fileInfo, fileTitle);
                    res.status(200).send(
                        {
                            ref: readStream.id,
                            type: fileType,
                            user: userId,
                            mediaInfo: fileInfo,
                            title: fileTitle
                        }
                    );
                })
                .on('error', () => {
                    res.status(500).send('error in writing with gridfs');
                })
                .pipe(writeStream);
            writeStream.on('close', function (file) {
                console.log(file.filename + 'written to DB');
                fs.unlink(myFile);
                myFile = null;
                conn.close();
            });
        });

        function writeToUserDb(uid, type, fileId, authInfo, title) {
            console.info('called to write to user db without a \'this\' reference');
            var userConn = mongoose.createConnection('mongodb://localhost/mean-auth', (error) => {
                if (error) {
                    console.error('Error connecting to the mean-auth instance'.red);
                    process.exit(1);
                } else {
                    User.findById(uid, (err, doc) => {
                        if (err) {
                            console.error('Error finding user with id: ', uid);
                            process.exit(1);
                        } else {
                            console.log('original doc: ', doc);
                            doc.addMedia(type, fileId, authInfo, title);
                            doc.save();
                            console.log('new doc: ', doc);
                        }
                    })
                }
            });
            userConn.close();
        }
    },

    downloadFile: function (userId, file, fileType, objId, location, res) {
        console.info('called to download file');
        var id = new mongodb.ObjectID(objId);
        var conn = mongoose.createConnection(mediaUri, (error) => {
            assert.ifError(error);

            var gfs = Grid(conn.db, mongoose.mongo);

            gfs.findOne({_id: id}, (err, result) => {
                if (err) {
                    res.status(400).send(err);
                } else if (!result) {
                    res.status(404).send('Error finding file')
                } else {
                    res.set('Content-Type', result.contentType);
                    res.set('Content-Disposition', 'attachment; filename="' + result.filename + '"');
                    var readStream = gfs.createReadStream({
                        _id: id,
                        root: 'resume'
                    });
                    readStream.on('error', (err) => {
                        res.end();
                    });
                    readStream.pipe(res);
                }
            });
        });
        conn.close();
    },

    deleteFile: function (userId, fileType, objId, res) {
        var client = mongodb.MongoClient;
        var id = new mongodb.ObjectID(objId);

        console.log('object id to find is: ', id);
        client.connect('mongodb://localhost/media', (err, db) => {
            db.collection('fs.files', {}, (err, files) => {
                files.remove({_id: id}, (err, result) => {
                    if (err) {
                        console.log(err);
                        res.status(500);
                    }
                    console.log(result);
                });
            });
            db.collection('fs.chunks', {}, (err, chunks) => {
                chunks.removeMany({files_id: id}, (err, result) => {
                    if (err) {
                        console.log(err);
                        res.status(500);
                    }
                    console.log(result);
                });
            });
            db.close();
        });
        res.status(200).send({id: userId, type: fileType, ref: id});
    },

    getAll: function (req, res) {
        var uid = req.query.id;
        var conn = mongoose.createConnection('mongodb://localhost/mean-auth', (err) => {
            if (err) {
                console.error('Error connecting to mean-auth instance to read all');
                process.exit(1);
            } else {
                User.findById(uid, (err, doc) => {
                    if (err) {
                        console.error('Error finding user with id: ', uid);
                        process.exit(1);
                    } else {
                        if (doc) {
                            console.log('original doc: ', doc);
                            res.status(200).send({media: doc.media});
                        } else {
                            res.status(200);
                        }
                    }
                })
            }
        });
    }
};
票数 1
EN

Stack Overflow用户

发布于 2019-04-09 22:40:59

如果按如下方式导入ObjectId对象:

代码语言:javascript
复制
const ObjectId = mongoose.Types.ObjectId;

与普通导入一样,您可以在文件的顶部编写删除操作,如下所示:

代码语言:javascript
复制
const mongoose = require('mongoose');
const Grid = require('gridfs-stream');
const ObjectId = mongoose.Types.ObjectId
Grid.mongo = mongoose.mongo // assign the mongo driver to the Grid

const mongooseURI = 'mongodb://localhost/media';
const conn = mongoose.createConnection(mongooseURI, {useNewUrlParser:true});

conn.once('open', () => {
        const gfs = Grid(conn.db);
        gfs.exist({_id: ref}, (err, found) => {
            if(err) {
                console.error('error finding file'.red);
            } else {
                console.info('found file', found);
                gfs.files.deleteOne({_id:new ObjectId(ref)}, (err, result) => {
                    if(err) {
                        console.error('error removing that file');
                        process.exit(1);
                    } else {
                        console.info('removed file: ', found.green);
                        deleteFromUserDb(id, type, ref);
                        res.status(200).send({id: id, type: type, ref: ref});
                    }
                });
            }
        });

希望这能有所帮助!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40010242

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档