You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose定义comments字段时ObjectId被当作值使用报错如何解决

错误原因
  • 报错本质是TypeScript类型与Mongoose运行时配置混用:ObjectId作为TS类型仅在编译阶段有效,不能直接作为Schema配置的type字段值使用(该字段需要传入运行时真实存在的构造函数)。
  • 你期望存储的comments结构中user为字符串类型的用户名,与当前定义的ObjectId类型不匹配,需要同步调整类型定义与Schema配置。
修复方案

方案1:直接存储用户名字符串(匹配你给出的目标存储结构)

调整TS接口与Schema配置,统一使用字符串类型:

// 接口定义部分
import { Document } from 'mongoose';

export interface Blog extends Document {
    ...
    comments: { user: string; comment: string }[]
    ...
}
// Schema 定义部分
import { Schema } from 'mongoose';

const blogSchema = new Schema<Blog>({
    ...
    comments: [
        {
            user: {
                type: String
            },
            comment: {
                type: String
            }
        }
    ],
    ...
})

方案2:关联用户表存储ObjectId,查询时填充用户名

如果你需要通过user字段关联用户集合,仅在查询时返回用户名,可使用该方案:

// 接口定义部分
import { Document, ObjectId } from 'mongoose';

export interface Blog extends Document {
    ...
    comments: { user: ObjectId; comment: string }[]
    ...
}
// Schema 定义部分
import { Schema } from 'mongoose';

const blogSchema = new Schema<Blog>({
    ...
    comments: [
        {
            user: {
                type: Schema.Types.ObjectId,
                ref: 'User' // 替换为你的用户表对应的Model名称
            },
            comment: {
                type: String
            }
        }
    ],
    ...
})

查询时调用populate方法即可得到你期望的返回结构:

// 查询示例,仅填充用户名字段
const blogList = await BlogModel.find().populate('comments.user', 'username');

内容的提问来源于stack exchange,提问作者VIVID

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:36:03