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

时间:2019-08-22 17:22:30

标签: node.js mongodb mongoose gridfs

所以我试图为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以上文件的人吗?为什么实施起来如此困难?谁能指导我朝正确的方向前进。

1 个答案:

答案 0 :(得分:1)

最新响应,但尝试将ref: 'tracks.files'替换为ref: 'trackSchema'

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

我也不建议创建用于实施GridFS的任何形式的架构,我会让Mongo来解决这个问题,因为如果实施不正确,可能会导致文件损坏或文档丢失/过时。

由于缺乏有关GridFS的官方文档,尤其是缺少带Mongoose的GridFS,我使用了Mongo的本机GridFsBucket类(据我所知,尚不存在官方的Mongoose-GridFS API),这是我自己尝试的最佳文档是gridfsstreaming此处提供教程。

要将Mongo的本机GridFSBucket与Mongoose一起使用,只需从其mongo属性中获取其connection属性和Mongoose的连接实例。

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