猫鼬未将其添加到同一对象

时间:2020-07-29 07:29:51

标签: mongodb mongoose

我有此结构的数据:

{
    "_id": "5f212467b57c1e693fd89060",
    "location":
        {
            "coordinates": [-31.802758, 115.837737],
            "type": "Point"
        },
    "store": "Liberty Landsdale",
    "__v": 0,
    "getdata": [
        {
            "2020-07-30":
                {"95": "1.14"}
        },
        {
            "2020-07-30":
                {"91": "1.02"}
        }
    ]
}

但是我希望它看起来像这样

{
    "_id": "5f212467b57c1e693fd89060",
    "location": {
        "coordinates": [-31.802758, 115.837737],
        "type": "Point"
    },
    "store": "Liberty Landsdale",
    "__v": 0,
    "getdata": [
        {
            "2020-07-30":
                [
                 {"95": "1.14"},
                 {"91": "1.02"}
                ]
        }
    ]
}

我知道问题是我将其插入mongodb的方式

mFuel.findOneAndUpdate(
    {'store': t, 'location': [{coordinates: [lat, long], type: "Point"}]},
    {$addToSet: {'getdata': {[d]: {[ftype]: p}}}}, {upsert: true}, 
    function (err) {
        if (err) {
            console.log('ERROR when submitting round');
            console.log(err);
        }
    });

我尝试了$push以及setaddToSet

我想知道实现目标的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以将$arrayFilters$set配合使用来实现此目的:

let d = '2020-07-30';
let setKey = `getdata.$[elem].${d}`;
let arrayFiltersKey = `elem.${d}`;
let col = await mFuel.updateOne(
    {
        'store': t, 'location': [{coordinates: [lat, long], type: 'Point'}]
    },
    {
        $addToSet: {
            [setKey]: {[ftype]: p}
        }
    },
    {
        arrayFilters: [
            {[arrayFiltersKey]: {$exists: true}},
        ]
    });

请注意,这不能与upsert一起使用,因为将arrayFilters与它一起使用会引发错误。

不管这个数据结构让我感到奇怪,我还是建议您将其更改为更易于使用的内容。

两个:

"getdata": [
    {
        k: "2020-07-30",
        v: [{"95": "1.14"}]
    }
]

"getdata": {
    "2020-07-30": [
        {"95": "1.14"}
    ]
}

--------------编辑-------------------

具有第二种结构:

let d = '2020-07-30';
let setKey = `getdata.${d}`;
let col = await mFuel.updateOne(
    {
        'store': t, 'location': [{coordinates: [lat, long], type: 'Point'}]
    },
    {
        $addToSet: {
            [setKey]: {[ftype]: p}
        }
    },
    {
        upsert: true
    });