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

Mongoose文档数组字段无法访问及更新问题求助

Mongoose文档数组字段无法访问及更新问题求助

各位大佬,我最近在Next.js里用Mongoose操作MongoDB时遇到了一个特别诡异的问题,折腾半天没找到根源,来求支招!

先给大家看我的代码配置:

type DemoSchema = { strings: string[] }
const DemoSchema = new Schema<DemoSchema>({
  strings: [String]
})

我手动在数据库里插了一条测试文档,结构是这样的:

{ _id: xxx, strings: ['hello'] }

然后我通过ID查询这个文档后,奇怪的现象出现了:

const demoDocument = await DemoModel.findById(submitID)
console.log(demoDocument) // 这里能正常输出完整文档:{ _id: xxx, strings: ['hello'] }
// 但直接访问这个字段却返回undefined!
console.log(demoDocument.strings) // 结果是undefined

更离谱的是更新数组的时候:

demoDocument.strings = ['New String']
console.log(demoDocument, demoDocument.strings)
// 打印整个文档还是原来的 { _id: xxx, strings: ['hello'] }
// 但单独取demoDocument.strings却能得到 ['New String']

新赋值的数组完全没同步到文档对象里。

我还试过其他几种更新方式,也都没效果:

  • 用demoDocument.strings.push(newString)添加元素
  • 直接通过下标赋值demoDocument.strings[0] = newString
  • 甚至手动调用demoDocument.markModified('strings')标记字段修改

补充下环境细节:MongoDB版本8.0.4,Mongoose版本8.16.0,所有代码都在Next.js项目中运行。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 10:53:00