用于填充文档mongoose 7.3.x的接口

v9tzhpje  于 2023-08-06  发布在  Go
关注(0)|答案(2)|浏览(90)

假设我有User模型,如below

import { Schema, model, Types, HydratedDocument } from "mongoose";

interface IUser {
  _id: Types.ObjectId;
  name: string;
  parent: Types.ObjectId;
}

interface IUserPopulate {
  parent: IUser;
}

type MergePopulate<I, IP> = Omit<HydratedDocument<I>, keyof IP> & IP;

const UserSchema = new Schema<IUser>({
  name: String,
  parent: { type: Schema.Types.ObjectId, ref: "users" },
});

const UserModel = model("users", UserSchema);

字符串
然后通过UserModel#find方法查找用户

async function getUser() {
  const users = await UserModel.find().populate<IUserPopulate>("parent");
  users.forEach((user) => {
    processUser(user);
  });
}


和函数处理用户接受填充的用户文档

async function processUser(user: MergePopulate<IUser, IUserPopulate>) {
//do some thing
}


Typescript在使用find()时接受用户文档,但在使用findOnefindById时不接受

const user = await UserModel.findOne().populate<IUserPopulate>("parent");

processUser(user); //throw alot of error here


如何为两个查询定义接口?
注意:这是为mongoose < 7工作,我只是在升级mongoose到7.3.0时得到这个错误

eiee3dmh

eiee3dmh1#

findOnefindById返回一个文档或null,因此您必须添加一个测试来消除它们返回null的情况:

const user = await UserModel.findOne().populate<IUserPopulate>("parent");
if(user) {
  processUser(user);
}

字符串
Playground

llew8vvj

llew8vvj2#

找到了

type MergePopulate<I, IP> = Omit<Document<unknown, {}, I & {
    _id: Types.ObjectId
  }> & Omit<I & {
    _id: Types.ObjectId
  } & Required<{
    _id: Types.ObjectId
  }>, never>, keyof IP> & IP

字符串
然后我可以使用合并填充的接口来填充文档

相关问题