【发布时间】:2013-03-13 08:59:54
【问题描述】:
我正在使用 mongoose 和 gridfs-stream 从 mongodb 存储和读取文件。我在这里遵循示例:https://github.com/aheckmann/gridfs-stream
将文件写入 db 工作正常,但读取文件时遇到问题。
mongodb 的外观(显示集合)
fs.chunks
fs.files
文件索引的样子 (db.fs.files.find())
{ "_id" : ObjectId("5140392659851df70b000001"),
"filename" : "cover",
"contentType" : "binary/octet-stream",
"length" : 85734,
"chunkSize" : 262144,
"uploadDate" : ISODate("2013-03-13T08:30:30.299Z"),
"aliases" : null,
"metadata" : null,
"md5" : "4476b26067daa0677978ba501308a35d" }
然后我使用此代码获取名为“cover”的文件
...
var gfs = Grid(mongoose.connection.db, mongoose.mongo)
var readstream = gfs.createReadStream('cover')
发生错误:
Error: cover does not exist
at self.collection.self.fileId (/mypath/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js:198:26)
at Cursor.nextObject (/mypath/node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursor.js:654:35)
at Cursor.close (/mypath/node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursor.js:960:5)
at Cursor.nextObject (/mypath/node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursor.js:654:17)
at Cursor.nextObject.commandHandler (/mypath/node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursor.js:631:14)
at Db._executeQueryCommand (/mypath/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js:1702:5)
at g (events.js:185:14)
at EventEmitter.emit (events.js:115:20)
at Server.Base._callHandler (/mypath/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/base.js:130:25)
at Server.connect.connectionPool.on.server._serverState (/mypath/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:517:20)
我google了一下,发现了一些可能的相关链接:
https://github.com/mongodb/node-mongodb-native/issues/621
Why gridfs get isn't working on file id (ObjectId) only by filename
【问题讨论】:
-
如果我用“5140392659851df70b000001”替换“文件名”,它可以工作:
var readstream = gfs.createReadStream('5140392659851df70b000001')。我猜原因与设置密钥有关? -
只是好奇,您是否将对该文件的引用存储在 mongoose 创建的文档中?我正在研究使用 GridFS,并且想知道人们如何实现它。
-
fs.files 存储文件的所有信息,而 fs.chunks 存储文件的数据。 Mongo 在 fs.files 中使用 ObjectId("5140392659851df70b000001") 来查找 fs.chunks 中的数据。所以 fs.files 存储了对真实数据块的引用。
标签: node.js mongodb mongoose gridfs