如何使用mongoose和NestJs返回mongoDB中的ObjectId?

roejwanj  于 2023-03-03  发布在  Go
关注(0)|答案(1)|浏览(226)

我正在NestJs和MongoDB中编写CRUD,我使用的是Mongoose。当我执行Get查询时,_id字段返回{ }。此外,它会给我带来“$__”的所有字段,我只想给我带来我保存的信息。我尝试了.toJSON()方法,但这只在我查询单个对象时有效。
这是服务的代码:

import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';

import {
  CreateInvoiceDto,
  FilterInvoicesDto,
  UpdateInvoiceDto,
} from '../dtos/invoice.dtos';

import { Invoice } from '../entities/invoice.entity';

@Injectable()
export class InvoicesService {
  constructor(
    @InjectModel(Invoice.name) private invoiceModel: Model<Invoice>,
  ) {}

  async findAll(params?: FilterInvoicesDto) {
    if (params) {
      const { limit, offset } = params;
      return await this.invoiceModel.find().skip(offset).limit(limit).exec();
    }
    return await this.invoiceModel.find().exec();
  }

  async findOne(id: string) {
    const invoice = await this.invoiceModel.findById(id).exec();
    if (!invoice) {
      throw new NotFoundException(`Invoice #${id} not found`);
    }
    return invoice.toJSON();
  }

这是数据库模块的代码:

import { Module, Global } from '@nestjs/common';
import { ConfigType } from '@nestjs/config';
import { MongooseModule } from '@nestjs/mongoose';
import { MongoClient } from 'mongodb';

import config from '../config';

@Global()
@Module({
  imports: [
    MongooseModule.forRootAsync({
      useFactory: (configService: ConfigType<typeof config>) => {
        const { connection, user, password, host, port, dbName } =
          configService.mongo;
        return {
          uri: `${connection}://${host}:${port}`,
          user,
          pass: password,
          dbName,
        };
      },
      inject: [config.KEY],
    }),
  ],
  providers: [
    {
      provide: 'MONGO',
      useFactory: async (configService: ConfigType<typeof config>) => {
        const { connection, user, password, host, port, dbName } =
          configService.mongo;
        const uri = `${connection}://${user}:${password}@${host}:${port}/?authSource=admin&readPreference=secondary`;
        const client = new MongoClient(uri);
        await client.connect();
        const database = client.db(dbName);
        return database;
      },
      inject: [config.KEY],
    },
  ],
  exports: ['MONGO', MongooseModule],
})
export class DatabaseModule {}

这是我得到的回答:

[
    {
        "$__": {
            "activePaths": {
                "paths": {
                    "total": "init",
                    "currencyCode": "init",
                    "exhangeRate": "init",
                    "igtf": "init",
                    "islr": "init",
                    "iva_p": "init",
                    "iva_r": "init",
                    "iva": "init",
                    "subtotal": "init",
                    "methodId": "init",
                    "invoiceNumber": "init",
                    "clientId": "init",
                    "_id": "init",
                    "registerDate": "init",
                    "__v": "init"
                },
                "states": {
                    "require": {},
                    "init": {
                        "_id": true,
                        "clientId": true,
                        "invoiceNumber": true,
                        "methodId": true,
                        "subtotal": true,
                        "iva": true,
                        "iva_r": true,
                        "iva_p": true,
                        "islr": true,
                        "igtf": true,
                        "exhangeRate": true,
                        "currencyCode": true,
                        "total": true,
                        "registerDate": true,
                        "__v": true
                    }
                }
            },
            "skipId": true
        },
        "$isNew": false,
        "_doc": {
            "_id": {},
            "clientId": 278,
            "invoiceNumber": 278,
            "methodId": "sjbdf,jbs",
            "subtotal": 11.5,
            "iva": 11.5,
            "iva_r": 11.5,
            "iva_p": 11.5,
            "islr": 11.5,
            "igtf": 11.5,
            "exhangeRate": 25.5,
            "currencyCode": "USD",
            "total": 11.5,
            "registerDate": "2023-02-24T17:00:39.404Z",
            "__v": 0
        }
    },
]

如果您查看响应,就会发现在true中有一个skipId属性,那么如何显示ObjectId并隐藏响应中的所有元数据呢?

3df52oht

3df52oht1#

尝试添加lean

async findAll(params?: FilterInvoicesDto) {
    if (params) {
      const { limit, offset } = params;
      return await this.invoiceModel.find().skip(offset).limit(limit).lean().exec();
    }
    return await this.invoiceModel.find().lean().exec();
  }

相关问题