#typescript #mongoose
Вопрос:
Я использую Мангуста для своего развития, и у меня есть модель территории, как показано ниже.
import mongoose from 'mongoose';
import { UserDoc, AgencyDoc } from '@ssomlk-org/distribution-common';
import { AreaDoc } from './Area';
// An interface that describes the properties
// that are required to create a new Territory
interface TerritoryAttrs {
area: string;
agency: string;
code: string;
description: string;
createdBy: string;
}
// An interface the describes the properties
// that a Territory model has
interface TerritoryModel extends mongoose.Model<TerritoryDoc> {
build(attrs: TerritoryAttrs): TerritoryDoc;
}
// An interface that descripbe the properties
// that a Territory document has
interface TerritoryDoc extends mongoose.Document {
area: AreaDoc;
agency: AgencyDoc;
code: string;
description: string;
status: string;
createdBy: UserDoc;
createdAt: string;
modifiedAt: string;
}
const TerritorySchema = new mongoose.Schema(
{
area: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Area',
required: true,
},
agency: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Agency',
required: true,
},
code: {
type: String,
required: true,
uppercase: true,
},
description: {
type: String,
required: true,
},
status: {
type: String,
enum: ['Active', 'Inactive'],
default: 'Active',
required: false,
},
createdBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: false,
},
createdAt: {
type: String,
required: false,
},
modifiedAt: {
type: String,
required: false,
},
},
{
toJSON: {
transform(doc, ret) {
ret.id = ret._id;
delete ret._id;
delete ret.__v;
},
},
}
);
TerritorySchema.index({ '$**': 'text' });
TerritorySchema.pre('save', async function (done) {
this.set('modifiedAt', new Date().toISOString());
if (this.isNew) {
this.set('createdAt', new Date().toISOString());
this.set('modifiedAt', undefined);
}
done();
});
TerritorySchema.statics.build = (attrs: TerritoryAttrs) => {
return new Territory(attrs);
};
const Territory = mongoose.model<TerritoryDoc, TerritoryModel>(
'Territory',
TerritorySchema
);
export { Territory, TerritoryDoc };
У меня есть API REST для получения территорий, как показано ниже
import express, { Request, Response } from 'express';
import { Document, DocumentQuery } from 'mongoose';
import {
ApiFeatures,
currentUser,
requireAuth,
} from '@ssomlk-org/distribution-common';
import { Territory, TerritoryDoc } from '../../models/Territory';
const router = express.Router();
router.get(
'/api/territories',
currentUser,
requireAuth,
async (req: Request, res: Response) => {
let resourceCount = 0;
const accessRoles = ['developer', 'admin'];
const role = req.currentUser!.role;
/************** GET RESOURCE TOTAL COUNT START **************/
let queryTotal: DocumentQuery<Document[], Document> = Territory.find({});
if (!accessRoles.includes(role)) {
queryTotal = queryTotal.where('agency').equals(req.currentUser!.agency);
}
const countTotalFeatures = new ApiFeatures(queryTotal, req.query)
.filter()
.sort()
.limitFields()
.search()
.strictFilter('agency', req.currentUser!.agency);
resourceCount = await countTotalFeatures._query.countDocuments();
/************** GET RESOURCE TOTAL COUNT END **************/
let query: DocumentQuery<Document[], Document> = Territory.find();
if (!accessRoles.includes(role)) {
query = query.where('agency').equals(req.currentUser!.agency);
}
const territoryFeatures = new ApiFeatures(query, req.query)
.filter()
.sort()
.limitFields()
.paginate(resourceCount.toString())
.search();
const territories = await territoryFeatures._query.populate([
{
path: 'createdBy',
select: ['firstName', 'lastName', 'email', 'role', 'status'],
},
{
path: 'area',
select: ['code', 'description', 'status'],
},
{
path: 'agency',
select: ['code', 'description', 'status'],
},
]);
const response = {
status: 'success',
data: {
results: territories.length,
total: resourceCount,
territories,
},
};
res.send(response);
}
);
export { router as getAllTerritoriesRouter };
I have updated mongoose and @types/mongoose to the latest and now I am getting the below error at line number 23.
Я уже некоторое время борюсь с этим, и может ли кто-нибудь помочь мне с этим, пожалуйста??
Овации