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

mongoose使用findByIdAndUpdate $push数组仅存储对象首个键值对如何解决

问题原因

你遇到的问题是Mongoose默认的Schema字段校验机制导致的:未在Schema中显式定义的字段,会被自动过滤不会写入数据库,你目前的Poll模型中responseAnswers数组的元素结构只定义了answer字段,没有声明text字段,所以只有answer的值被存入了数据库。

解决方法

  1. 找到你的Poll模型对应的Schema定义,修改responseAnswers字段的结构,显式声明所有需要存储的子字段:
// 修正后的Poll Schema示例
const mongoose = require('mongoose');
const PollSchema = new mongoose.Schema({
  // 你原有定义的其他字段,比如id、标题、选项等
  title: String,
  // 修正responseAnswers的子字段定义
  responseAnswers: [
    {
      answer: String,
      text: String
    }
  ]
});
module.exports = mongoose.model('Poll', PollSchema);
  1. 如果你后续可能需要往responseAnswers的元素中动态添加未提前定义的字段,可以给子文档关闭严格模式:
responseAnswers: [
  {
    answer: String,
    text: String,
    strict: false // 允许存储未在此处声明的额外字段
  }
]

不建议直接给整个Poll Schema关闭严格模式,容易存入无效脏数据。

修改Schema后新写入的pushedVote对象就会正常保存两个字段的内容。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 00:36:03