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
$pushtells MongoDB we want to add elements to an array.- The dynamic path
${name}.${language}resolves todescription.en, correctly targeting the nested array in your document. $eachlets us pass an array of elements to add (even a single element, like in your case).$position: 0ensures 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
相关产品推荐
相关产品推荐

