Mongoose Populate的严格类型化

l2osamch  于 2023-06-30  发布在  Go
关注(0)|答案(1)|浏览(135)

是否有任何方法来定义/修改接口或类型,以 * Assert * 文档将使用mongoose填充到typescript中?
例如

interface ISchool {
   name: string;
   address; string;
}
interface IPerson {
   name: string;
   school?: PopulatedDoc<ISchool & Document>
}
const PersonSchema: Schema<IPerson> = new Schema<IPerson>({
    name: { type: String },
    school: { type: Schema.Types.ObjectId, ref: 'School' }
})
const Person = mongoose.model<IPerson>('Person', PersonSchema);
export default Person

然后,本质上,如果我们与Person文档交互,就没有办法知道school属性是否被填充。例如。

const person = await Person.findOne({});
if (person.school) { . . . } // is `school` an ObjectId or a Document?

const person = await Person.findOne({}, undefined, { populate: { path: 'school', model: 'School'} });
if (person.school) { . . . } // is `school` an ObjectId or a Document?

是否有任何方法可以Assert文档属性已被填充?
谢谢

xiozqbni

xiozqbni1#

populate-with-typescript文档中,我们可以:
将泛型参数Paths添加到populate()

import mongoose, { Types } from 'mongoose';

interface ISchool {
    name: string;
    address: string;
}
interface IPerson {
    name: string;
    school?: Types.ObjectId;
}
const PersonSchema: mongoose.Schema<IPerson> = new mongoose.Schema<IPerson>({
    name: { type: String },
    school: { type: mongoose.Schema.Types.ObjectId, ref: 'School' },
});

const Person = mongoose.model<IPerson>('Person', PersonSchema);

(async function run() {
    const person1 = await Person.findOne({});
    person1?.school; // school is ObjectId

    const person2 = await Person.findOne({}).populate<{ school: ISchool }>({ path: 'school', model: 'School' });
    person2?.school; // scholl is ISchool
})();

相关问题