我需要将一个对象添加到数组的第一个位置。在此示例中,它是数组 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:“description.en”中的虚线字段“description.en”对于存储无效。
最佳答案
您需要使用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
}
}
}
关于javascript - MongoDB:虚线字段对于存储无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49602282/