我有一个正确的模式User
,其中默认写入字段_id
、createdAt
和updatedAt
,但在模式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 },
);
}
怎么解决呢?
1条答案
按热度按时间o8x7eapl1#
固定id,正确实现: