【问题标题】:nodejs gridfs grid.put() with identical filename overwrites file具有相同文件名的nodejs gridfs grid.put()覆盖文件
【发布时间】:2023-04-05 13:40:01
【问题描述】:

当我使用 grid.put() 将文件写入 GridFS 时,它与之前存储的文件具有相同的文件名,第一个文件将被覆盖。同一个文件名在数据库中只能存在一次,这是真的还是我做错了什么?

我的代码如下所示:

var mongo = require('mongodb'),
  Server = mongo.Server,
  Db = mongo.Db,
  Grid = mongo.Grid;
  server = new Server('localhost', 27017, {auto_reconnect: true});
  db = new Db('mydb', server);

db.open(function(err, db) {
  var buffer = new Buffer("This is the first sample text");
  grid.put(buffer, {metadata:{}, filename: "test.txt", content_type: 'text'}, function(err, fileInfo) {
    buffer = new Buffer("This is the second sample text");
    // now this overwrites the first one...
    grid.put(buffer, {metadata:{}, filename: "test.txt", content_type: 'text'}, function(err, fileInfo) {
    });
  });
});

我认为该文件是由 ._id ObjectId 而不是由文件名指定的唯一的。我错了吗?

感谢您的帮助!

【问题讨论】:

    标签: node.js mongodb gridfs


    【解决方案1】:

    根据GridFS spec,文件由_id 索引。文件名是元数据的一部分,不必是唯一的。如果您两次放置具有相同文件名的内容,您应该能够通过在命令行中使用 mongofiles list 来确认这两个文件都存在。

    您使用的是哪个版本的 MongoDB Node.js 驱动程序?似乎几个月前纠正了一个驱动程序错误:Cannot save files with the same file name to GridFS

    【讨论】:

    • 谢谢!这是一个有用的答案。
    【解决方案2】:

    是的,它们被覆盖了,就像在真实的文件系统上一样! _id 对 MongoDB 内部(以及标准文档)是必不可少的,但是当您使用 GridFS 文件时,_id 字段无关紧要,文件名必须是唯一的。

    另外:当您grid.get 时,您希望收到什么?第一个文件?第二?两者结合?

    【讨论】:

    • 您的问题假设 grid.get() 的参数是 。但事实并非如此!由于documentation 它是。因此,尽管事实上还有其他具有相同名称的文档,但我希望得到具有此 _id 的文档。
    猜你喜欢
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 1970-01-01
    相关资源
    最近更新 更多