Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create mongoose model for GridFS collection?

So I am trying to create a mongoose model for GridFS collection but to no success.

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);
    }
})();

Here is my course schema and model:

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

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

And here is my tracks schema and model:

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);

And I am getting this error:

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

when I run this:

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

There is absolutely zero documentation on these stuff and I am going insane over it. Am I the first person to ever save 16 MB+ files in Mongodb? Why is it so difficult to implement this? Can anyone please guide me to the right direction.

like image 379
Anonymous Avatar asked Jan 25 '23 22:01

Anonymous


1 Answers

Late response but try replacing ref: 'tracks.files' with ref: 'trackSchema'.

The ref field is referenced within populate('trackSchema') and must be a reference to another Schema. Check saving-refs out if you want to learn more about populating fields and references in Mongoose.

I also wouldn't recommend creating schemas of any sort for implementing GridFS, I'd let Mongo take care of this as it may lead to file corruption or missing/outdated documents if implemented incorrectly.

As for the lack of official documentation for GridFS, especially GridFS with Mongoose, I used Mongo's native GridFsBucket class (as of my knowledge, no still maintained official Mongoose-GridFS API exist), the best docs I used when attempting this myself was gridfs. With a tutorial here streaming.

To use Mongo's native GridFSBucket with Mongoose just grab its mongo property and Mongoose's connection instance from its connection property.

const mongoose = require(mongoose);
var gridFSBucket = new mongoose.mongo.GridFSBucket(mongoose.connection.db, {
   bucketName: 'images'
});
like image 52
codeguy Avatar answered Jan 29 '23 06:01

codeguy