Я работаю с динамическими c коллекциями, то есть каждый клиент в моем приложении имеет свои собственные коллекции, поэтому я должен иметь возможность отправлять ему имена из маршрута, где я вызываю эту модель, из моего маршрута в том, что я хочу иметь возможность передавать ему эти имена коллекций, чтобы он мог работать с коллекциями каждого клиента
// router
router.get(
'/:id',
jwtAuthz(['read:documents'], options),
async (req, res, next) => {
const { id } = req.params
const collection = await getCollection(req)
let documents
try {
const Document = model(`${collection}documents`, DocumentsSchema)
console.log(Document)
documents = await Document.find({ drive: id })
res.json(documents)
} catch (err) {
next(err)
}
}
)
//model
// Dependencies
import { Schema, model } from 'mongoose'
const DocumentsSchema = new Schema(
{
document: {
type: String,
required: true
},
description: {
type: String,
required: true
},
type: {
type: String,
required: true
},
expiration: {
type: Boolean,
required: true
},
recipient: {
type: String,
required: true
},
approver1: {
type: String,
required: false
},
approver2: {
type: String,
required: false
},
approver3: {
type: String,
required: false
},
file: {
type: String,
required: false
},
formId: {
type: String,
required: false
},
first: {
type: Boolean,
required: true,
default: false
},
drive: {
type: String,
required: false
}
}
// {
// collection: 'documents'
// }
)
DocumentsSchema.virtual('userDocument', {
ref: 'DocumentUser', // the model to use
localField: '_id', // find children where 'localField'
foreignField: 'document', // is equal to foreignField
justOne: true // if return an Object or an Array
})
DocumentsSchema.set('toObject', { virtuals: true })
DocumentsSchema.set('toJSON', { virtuals: true })
const Documents = model('Document', DocumentsSchema)
export { Documents, DocumentsSchema }