MongoDB:虚线字段对存储无效

时间:2018-04-01 20:22:04

标签: javascript mongodb

我需要在第一个位置向数组添加一个对象。在此示例中,它是数组description.en

所以这是我的文档结构:

{
  _id: 'Aw5szXgeujrbhwY2r',
  description: {
    en: [
      {
        content: 'Need to change this',
        timestamp: 1480186254
      }
    ]
  }
}

这就是我尝试这样做的方式:

const name = 'description' // need to be dynamic
const language = 'en' // need to be dynamic

update = {
  [name + '.' + language]: {
    $position: 0,
    $each: [{
      content: 'New content',
      timestamp: Math.floor(Date.now() / 1000)
    }]
  }
}

return Content.update({ _id }, update)

但我收到错误MongoError: The dotted field 'description.en' in 'description.en' is not valid for storage.

1 个答案:

答案 0 :(得分:2)

您需要使用mongo的$push运算符:https://docs.mongodb.com/manual/reference/operator/update/push/#up._S_push

update = {
  $push: {
    [name + '.' + language]: {
       $position: 0,
       $each: [{
         content: 'New content',
         timestamp: Math.floor(Date.now() / 1000)
      }]
    }
  }
}

您还可以使用带有点表示法的$set来指定元素

update = {
  $set: {
    [name]: {
       [language + '.0']: {
          content: 'New content',
          timestamp
       }
    }
}