简体   繁体   English

Mongoose/NestJs 无法访问 createdAt 即使 {timestamps: true}

[英]Mongoose/NestJs can't access createdAt even though {timestamps: true}

I'm currently using Mongoose and NestJs and I'm struggling a bit regarding accessing the createdAt property.我目前正在使用 Mongoose 和 NestJs,我在访问 createdAt 属性方面遇到了一些困难。

This is my user.schema.ts这是我的 user.schema.ts

@Schema({ timestamps: true})
export class User {
  @Prop({ required: true })
  name!: string;

  @Prop({ required: true })
  email!: string;
}

export const UserSchema = SchemaFactory.createForClass(User);

and in my user.service.ts在我的 user.service.ts 中

public async getUser(
    id: string,
  ): Promise<User> {
    const user = await this.userModel.findOne({ id });

    if (!user) {
      throw new NotFoundException();
    }

    console.log(user.createdAt) // Property 'createdAt' does not exist on type 'User' .ts(2339)
  }

So basically I've set timestamps to true but I'm still unable to access the createdAt property.所以基本上我已经将时间戳设置为 true 但我仍然无法访问 createdAt 属性。 By the way I also have a custom id which works fine so please ignore that in my service.ts顺便说一下,我还有一个自定义 ID 可以正常工作,所以请在我的 service.ts 中忽略它

I've tried setting @Prop() createdAt?: Date to the schema but it still hasn't worked.我已经尝试将@Prop() createdAt?: Date设置为模式,但它仍然没有用。

I've also tested this schema using MongoMemoryServer and Jest which shows that it returns createdAt.我还使用 MongoMemoryServer 和 Jest 测试了这个模式,这表明它返回了 createdAt。

Any help as to why I can't access the createdAt property would be greatly appreciated!对于为什么我无法访问 createdAt 属性的任何帮助,我们将不胜感激!

I have tested using this:我已经测试过使用这个:

@Schema({ timestamps: true })

Then, I have added 2 fields in my model/entity (createdAt, updatedAt) to expose in the controller/resolver in NestJS.然后,我在我的模型/实体(createdAt、updatedAt)中添加了 2 个字段,以在 NestJS 的控制器/解析器中公开。

@Prop()
  @Field(() => Date, { description: 'Created At' })
  createdAt?: Date

  @Prop()
  @Field(() => Date, { description: 'Updated At' })
  updatedAt?: Date

Final example:最后的例子:

import { ObjectType, Field } from '@nestjs/graphql'
import { Schema as MongooseSchema } from 'mongoose'
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'
@Schema({ timestamps: true })
@ObjectType()
export class Post {
  @Field(() => String)
  _id: MongooseSchema.Types.ObjectId
  @Prop()
  @Field(() => String, { description: 'Post Body ' })
  body: string

  @Prop()
  @Field(() => Date, { description: 'Created At' })
  createdAt?: Date

  @Prop()
  @Field(() => Date, { description: 'Updated At' })
  updatedAt?: Date
}

export const PostSchema = SchemaFactory.createForClass(Post)

Now, My new fields createdAt, updatedAt are available:现在,我的新字段 createdAt、updatedAt 可用: 在此处输入图像描述

I tested your code, adding @Prop() createdAt?: Date should be able to access createdAt .我测试了您的代码,添加了@Prop() createdAt?: Date应该能够访问createdAt

The only thing I spot from your code where you cannot access createdAt is the id you pass to the query.我从您的代码中发现的唯一无法访问 createdAt 的是您传递给查询的id The key should be _id键应该是_id

public async getUser(
    id: string,
): Promise<User> {
    const user = await this.userModel.findOne({ _id: id });

    if (!user) {
      throw new NotFoundException();
    }

    console.log(user.createdAt)
}

Here is the screenshot of my testing using your code:这是我使用您的代码进行测试的屏幕截图:

https://i.imgur.com/6JzVAyz.png https://i.imgur.com/6JzVAyz.png

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 MongoDB 中的 CreatedAt 无法排序 - CreatedAt in MongoDB can´t be sorted 即使应该,if语句也不会返回任何TRUE - The if statement doesn't return anything TRUE even though it should 即使可以看到对象的内容,也无法访问其属性 - I can't access the properties of an object even though I can see it's contents 即使我看到它们存在也无法访问对象属性 - Can't access object properties even though I can see they exist 即使存在窗口级别变量也无法访问。 访问时返回undefined - Can't access the window level variable even though it exists. returns undefined when accessed 无法访问属性 "innerHTML", document.getElementById('id' +num) 即使 js 在末尾声明 - can't access property "innerHTML", document.getElementById('id' +num) even though js is declared at the end of <body> 即使存在React对象状态,也无法访问对象属性。 返回未定义 - Can't access object property on a React object state, even though it exists. Returns undefined 无法访问 object 属性,即使它显示在控制台日志中 - Can't access object property, even though it shows up in a console log Mongoose 按 createdAt 排序 - Mongoose sorting by createdAt 用猫鼬操纵createdAt字段 - Manipulate createdAt field with mongoose
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM