ffx*_*292 12 javascript mongoose mongodb typescript nestjs
我目前正在使用 Mongoose 和 NestJs,并且在访问createdAt属性方面遇到了一些困难。
这是我的 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);
Run Code Online (Sandbox Code Playgroud)
在我的 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)
}
Run Code Online (Sandbox Code Playgroud)
所以基本上我已经将时间戳设置为 true 但我仍然无法访问createdAt属性。顺便说一句,我还有一个可以正常工作的自定义 id,因此请在我的 service.ts 中忽略它
我已经尝试设置@Prop() createdAt?: Date架构,但仍然不起作用。
我还使用 MongoMemoryServer 和 Jest 测试了此模式,显示它返回createdAt。
关于为什么我无法访问createdAt属性的任何帮助将不胜感激!
wil*_*ola 11
我已经使用这个进行了测试:
@Schema({ timestamps: true })
Run Code Online (Sandbox Code Playgroud)
然后,我在模型/实体中添加了 2 个字段(createdAt、updatedAt)以在 NestJS 的控制器/解析器中公开。
@Prop()
@Field(() => Date, { description: 'Created At' })
createdAt?: Date
@Prop()
@Field(() => Date, { description: 'Updated At' })
updatedAt?: Date
Run Code Online (Sandbox Code Playgroud)
最后的例子:
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)
Run Code Online (Sandbox Code Playgroud)
现在,我的新字段createdAt、updatedAt可用:

我测试了你的代码,添加@Prop() createdAt?: Date应该能够访问createdAt.
我从您的代码中发现您无法访问createdAt的唯一一件事是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)
}
Run Code Online (Sandbox Code Playgroud)
这是我使用您的代码进行测试的屏幕截图: