mongoose 如何在默认情况下将时间戳字段和_id添加到嵌套模式中

1hdlvixo  于 2023-02-23  发布在  Go
关注(0)|答案(1)|浏览(116)

我有一个正确的模式User,其中默认写入字段_idcreatedAtupdatedAt,但在模式Message中它不起作用。

export type UserDocument = HydratedDocument<User>;

@Schema({ timestamps: true, versionKey: false })
export class Message {
  @Prop()
  content: string;
}

@Schema({ timestamps: true, versionKey: false })
export class User implements UserInterface {
  @Prop()
  name: string;
  @Prop()
  email: string;
  @Prop([{ type: mongoose.Schema.Types.ObjectId, ref: 'Message' }])
  messages?: Message[];
}

export const UserSchema = SchemaFactory.createForClass(User);

下面是我创建消息的函数:

async createMessage() {
    const user = await this.userModel.findById('63ee4fc044d93a4f6bebf934');
    user.messages.push({ content: 'a' });
    return await user.save();
  }

错误是:

Cast to ObjectId failed for value "{ content: 'a' }" (type Object) at path "messages" because of "BSONTypeError"

但是下面这个代码段工作正常:

async createUser(createUserDto: CreateUserDto): Promise<CreatedUserDto> {
    return this.userModel.findOneAndUpdate(
      { name: createUserDto.name },
      createUserDto,
      { upsert: true, new: true },
    );
  }

怎么解决呢?

o8x7eapl

o8x7eapl1#

固定id,正确实现:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument } from 'mongoose';
import { UserInterface } from '../interface/user.interface';

export type UserDocument = HydratedDocument<User>;

@Schema({ timestamps: true, versionKey: false })
export class Message {
  @Prop()
  content: string;
}

export const MessageSchema = SchemaFactory.createForClass(Message);

@Schema({ timestamps: true, versionKey: false })
export class User implements UserInterface {
  @Prop()
  name: string;
  @Prop()
  email: string;
  @Prop({ type: [MessageSchema], default: [] })
  messages?: Message[];
}

export const UserSchema = SchemaFactory.createForClass(User);

相关问题