在查询或创建 mongoose 文档(在 NestJS 中)时如何排除 _id 和 __v 属性?

问题描述 投票:0回答:1

在我的 NestJS 后端应用程序中,我有这个用户架构:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema({
  versionKey: false,
  toJSON: { virtuals: true, getters: true },
  id: false,
})
export class User {
  @Prop({ required: true, unique: true })
  email: string;

  @Prop({ required: true })
  name: string;
}

export type UserDocument = User & Document;

export const UserSchema = SchemaFactory.createForClass(User);

UserSchema.virtual('id').get(function () {
  return this._id.toHexString();
});

当我查询时:

async findUserWithId(id: mongoose.Types.ObjectId): Promise<User> {
    return this.userModel.findById(id);
  }

  async findUserWithEmail(email: string): Promise<UserDocument> {
    return this.userModel.findOne({ email }).exec();
  }

或创建:

 const newUser = await new this.userModel(regsiterUserDto).save();

我的回复仍然包括

_id
属性。我希望这是
id

"user": {
        "email": "[email protected]",
        "name": "Dummy Name",
        "_id": "64ef0ef71e64e37bb88f953d"
    },

如何在不操作对象的情况下实现此目的(手动删除 _id)。

typescript mongoose nestjs mongoose-schema
1个回答
0
投票

您可以使用 Mongoose

select
语法来排除查询中的字段 https://mongoosejs.com/docs/api/query.html#Query.prototype.select()

例如,

// exclude _id, include other fields
async findUserWithId(id: mongoose.Types.ObjectId): Promise<User> {
    return this.userModel.findById(id).select('-_id');
}

从上面的文档中,

指定要包含或排除的文档字段(也称为查询“投影”)。

使用字符串语法时,在路径前添加 - 前缀将将该路径标记为已排除。当路径没有 - 前缀时,它将被包含在内。最后,如果路径以 + 为前缀,则会强制包含该路径,这对于在架构级别排除的路径很有用。

© www.soinside.com 2019 - 2024. All rights reserved.