如何为GridFS集合创建mongoose模型?

6

我试图为GridFS集合创建一个mongoose模型,但是一直没有成功。

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的文件吗?为什么实现这个如此困难?有人能否请指导我正确的方向。

1个回答

11
晚了一点回复,但是试着用 ref: 'trackSchema' 替换 ref: 'tracks.files'ref 字段在 populate('trackSchema') 内被引用,必须是指向另一个模式的引用。如果您想要学习更多关于在 Mongoose 中填充字段和引用的内容,请查看saving-refs
我也不建议为了实现 GridFS 而创建任何类型的模式,我会让 Mongo 来处理这个问题,因为如果实现不正确,它可能会导致文件损坏或缺失/过时的文档。
至于 GridFS 缺乏官方文档的问题,特别是与 Mongoose 结合使用的 GridFS,我使用了 Mongo 的原生 GridFsBucket 类(据我所知,还没有维护良好的官方Mongoose-GridFS API),我尝试自己实现时使用的最佳文档是gridfs。 还有一个教程streaming
要使用 Mongo 的原生 GridFSBucket 与 Mongoose 一起使用,只需获取其 mongo 属性和 Mongoose 的连接实例即可从其 connection 属性中获取。
const mongoose = require(mongoose);
var gridFSBucket = new mongoose.mongo.GridFSBucket(mongoose.connection.db, {
   bucketName: 'images'
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接