因此,我试图为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: 'tracks.files'
替换为ref: 'trackSchema'
。 ref
字段在populate('trackSchema')
中引用,并且必须是对另一个架构的引用。如果要了解有关在Mongoose中填充字段和引用的更多信息,请检查https://mongoosejs.com/docs/populate.html#saving-refs。我也不建议为实现GridFS创建任何形式的架构,我会让Mongo来解决这个问题,因为如果实施不正确,可能会导致文件损坏或文档丢失/过时。由于缺乏GridFS的官方文档,特别是缺少带Mongoose的GridFS,我使用了Mongo的本机GridFsBucket类(据我所知,尚不存在官方的Mongoose-GridFS API),在尝试本人时使用的最佳文档是[C0 ]。这里有一个教程http://mongodb.github.io/node-mongodb-native/3.5/api/GridFSBucket.html。
要在Mongoose中使用Mongo的本机GridFSBucket,只需从其http://mongodb.github.io/node-mongodb-native/2.1/reference/gridfs/streaming/属性中获取其mongo
属性和Mongoose的连接实例。
connection