如何为 GridFS 集合创建猫鼬模型?

How to create mongoose model for GridFS collection?

所以我正在尝试为 GridFS 集合创建猫鼬模型,但没有成功。

let bucket;
(async () => {
    try {
        await mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true });
        const { db } = mongoose.connection;
        bucket = new mongoose.mongo.GridFSBucket(db, { bucketName: 'tracks' });
    }
    catch(err) {
        console.log(err);
    }
})();

这是我的课程架构和模型:

const courseSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    tracks: [{
        type: mongoose.Types.ObjectId,
        ref: 'tracks.files'
    }],
});

const Course = mongoose.model('Course', courseSchema);

这是我的足迹架构和模型:

const trackSchema = new mongoose.Schema({
    length: { type: Number },
    chunkSize: { type: Number },
    uploadDate: { type: Date },
    filename: { type: String, trim: true, searchable: true },
    md5: { type: String, trim: true, searchable: true },
}, { collection: 'tracks.files', id: false });

const Track = mongoose.model('Track', trackSchema);

我收到这个错误:

MongooseError [MissingSchemaError]: Schema hasn't been registered for model "tracks.files".

当我运行这个:

Course.findById('5d5ea99e54fb1b0a389db64a').populate('tracks').exec()
    .then(test => console.log(test))
    .catch(err => console.log(err));

关于这些东西的文档绝对为零,我快要疯了。我是第一个在 Mongodb 中保存 16 MB+ 文件的人吗?为什么实施起来如此困难?谁能指导我正确的方向。

回复晚了,但请尝试用 ref: 'trackSchema' 替换 ref: 'tracks.files'

ref 字段在 populate('trackSchema') 中被引用,并且必须是对另一个架构的引用。如果您想了解有关在 Mongoose 中填充字段和引用的更多信息,请查看 saving-refs

我也不建议为实施 GridFS 创建任何类型的模式,我会让 Mongo 处理这个问题,因为如果实施不当可能会导致文件损坏或 missing/outdated 文档.

关于GridFS官方文档的缺失,尤其是GridFS with Mongoose,我用的是Mongo原生的GridFsBucket class(据我所知,目前还没有维护官方 Mongoose-GridFS API 存在),我自己尝试时使用的最好的文档是 gridfs. With a tutorial here streaming.

要将 Mongo 的原生 GridFSBucket 与 Mongoose 一起使用,只需从其 [=16] 中获取其 mongo 属性 和 Mongoose 的连接实例=] 属性.

const mongoose = require(mongoose);
var gridFSBucket = new mongoose.mongo.GridFSBucket(mongoose.connection.db, {
   bucketName: 'images'
});