mongodb 如何在node.js中使用typescript和模型接口填充mongdb包

fcg9iug3  于 2023-05-28  发布在  Go
关注(0)|答案(1)|浏览(129)

我将typescript用于这个接口(模型的),名为invoice.ts:

import { ObjectId } from "mongodb";

interface Invoice {
 _id: ObjectId;
 accountId: ObjectId;
 number: string;
 invoiceDate: Date;
 amount: number;
 paymentDate: Date;
 expectedPaymentDate: Date;
 updatedAt: Date;
 createdAt: Date;
 paymentAt: Date;
 repaymentAt: Date;
 reservation: object;
 totalCosts: number;
}

export { Invoice };

我想检索所有具有accountId名称的发票,accountId是一个对象,发票的number + id + createdAt
在服务-贷款.ts
我试过这个:

import { Invoice } from "../models/invoice";
  import { MongoClient } from "mongodb";
  import logger from "../lib/logging/logger";

  const url: string = process.env["MONGODB_URL"] || "";
  const dbName: string = process.env["MONGODB_DATABASE"] || "";
  const client = new MongoClient(url);

  const getInvoices = async () => {
   try {
    await client.connect();
    const db = client.db(dbName);
    const invoiceCollection = db.collection<Invoice>("invoice");
    const invoices = await invoiceCollection
     .find(
      {},
       {
        projection: {
         accountId: 1,
         number: 1,
         id: 1,
         createdAt: 1,
        },
       },
      )
      .populate([{ path: "accountId", select: "name" }])
      .lean();
   }
   catch (error) {
    logger.error(error);
   }

 };
 export default { getInvoices };

它给出了一个错误,populate说:类型上不存在属性“populate”。ts(2339).我需要路径的名称“accountId”
有谁知道如何使查询正确吗?

szqfcxe2

szqfcxe21#

不幸的是,mongoDB本身不支持population
我将使用mongoose库或在聚合(documentation)中执行lookup

相关问题