【问题标题】:mongo schema creates empty object with idmongo 模式创建具有 id 的空对象
【发布时间】:2021-09-17 01:20:53
【问题描述】:

我正在尝试创建一个新的 mongo 对象,但下面的代码返回一个只有 id 的空对象。我做错了什么,我只是看不到错误。调用时没有返回错误,只是一个空对象。 这是 Nest js 应用程序

    const newComment = new this.commentModel({
      name: user.name,
      avatar: user.avatar,
      user: userId,
      text: text,
    });

这是我的架构:

Schema();
class Comment {
    @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' })
    user: User;

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

    @Prop()
    name: string;

    @Prop()
    avatar: string;

    @Prop({ default: Date.now })
    date: Date;
}

export const CommentSchema = SchemaFactory.createForClass(Comment);

谁能帮我解决这个问题?

【问题讨论】:

    标签: typescript mongodb mongoose nestjs mongoose-schema


    【解决方案1】:

    所以这里有几件事是关闭的,首先模式装饰应该是@Schema 而不是Schema。然后你必须导出类本身然后最后等待创建结果。所以把它们放在一起就是

    **创建新评论**

    const newComment = await new this.commentModel({
      name: user.name,
      avatar: user.avatar,
      user: userId,
      text: text,
    });
    

    架构现在应该是

    @Schema();
    export class Comment {
        @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' })
        user: User;
    
        @Prop({ required: true })
        text: string;
    
        @Prop()
        name: string;
    
        @Prop()
        avatar: string;
    
        @Prop({ default: Date.now })
        date: Date;
    }
    
    export const CommentSchema = SchemaFactory.createForClass(Comment);
    

    如果你有一个 UserSchema,我猜你有,你可以更改对 User.name 的引用以确保类型安全,现在看起来像

        @Schema();
        export class Comment {
            @Prop({ type: mongoose.Schema.Types.ObjectId, ref: User.name })
            user: User;
        
            @Prop({ required: true })
            text: string;
        
            @Prop()
            name: string;
        
            @Prop()
            avatar: string;
        
            @Prop({ default: Date.now })
            date: Date;
        }
    export const CommentSchema = SchemaFactory.createForClass(Comment);
    

    【讨论】:

    • 伙计,你是救生员!我有同样的问题,我只是看不到它。浪费了太多时间!谢谢!!
    猜你喜欢
    • 2019-01-27
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 2023-02-04
    • 2016-01-10
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多