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

MongoDB报错:点字段存储无效,如何向数组首位添加对象?

Fixing "Dotted field is not valid for storage" When Prepending to a Nested MongoDB Array

Let's break down why you're hitting this error and how to fix it quickly.

The Root Cause

Your current update syntax is trying to create a top-level field named description.en (with a dot in the name), which MongoDB doesn't allow for stored fields. What you actually want to do is target the nested en array inside the description object, but your approach is structuring the update incorrectly.

Correct Implementation

You need to use the $push operator (with its $each and $position modifiers) and dynamically reference the nested array path properly. Here's how to adjust your code:

const name = 'description'; // Dynamic field name
const language = 'en'; // Dynamic language code
const newContent = { 
  content: 'New content', 
  timestamp: Math.floor(Date.now() / 1000) 
};

// Build the update object correctly
const update = {
  $push: {
    // Use template literals to dynamically create the nested path
    [`${name}.${language}`]: {
      $each: [newContent],
      $position: 0 // Insert at the start of the array
    }
  }
};

// Example usage with updateOne
await db.collection('your-collection-name').updateOne(
  { _id: 'Aw5szXgeujrbhwY2r' }, // Match your document by _id
  update
);

How This Works

  • $push tells MongoDB we want to add elements to an array.
  • The dynamic path ${name}.${language} resolves to description.en, correctly targeting the nested array in your document.
  • $each lets us pass an array of elements to add (even a single element, like in your case).
  • $position: 0 ensures the new element gets inserted at the beginning of the array, which is exactly what you're aiming for.

Verification

After running this update, your document should look like this:

{ 
  _id: 'Aw5szXgeujrbhwY2r', 
  description: { 
    en: [ 
      { content: 'New content', timestamp: /* current unix timestamp */ },
      { content: 'Need to change this', timestamp: 1480186254 } 
    ] 
  } 
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:04:01