簡體   English   中英

使用變量(MongoDB,Node,Inc)訪問嵌套數組中的嵌套對象

[英]Accessing nested object in nested array using a variable (MongoDB, Node, Inc)

我知道與此問題相關的主題眾多,但似乎沒有一個問題可以回答我的問題。 它與Node和Mongo有關,但是我認為這是一個通用的Javascript問題。

在MongoDB中,我需要使用給出索引號的變量訪問options數組,然后遞增其votes屬性。 一個例子是:

{
    "_id": {
        "$oid": "58ce7c6c39aff90a7c66b0d4"
    },
    "question": "Test",
    "options": [
        {
            "answer": "answer1",
            "option": "Bob Dylan",
            "votes": 2
        },
        {
            "answer": "answer2",
            "option": "Bob Geldof",
            "votes": 0
        }
    ]
}

然后,我得到需要更新的數組的索引,如下所示:

var votedFor = "answer2";
votedFor = votedFor.match(/\d+/)[0];
var index = parseInt(votedFor) - 1;

然后我假設要遞增的整數的路徑為:

var inc = {};
inc["options[" + index + "].votes"] = 1;

我想這樣傳遞:

db.collection('questions')
.findOneAndUpdate({"_id": questionId}, {$inc : inc }, (err, result) => {
  if (err) return res.send(err)
  res.send(result)
})

哪個像這樣更新數據庫:

    {
        "_id": {
            "$oid": "58ce7c6c39aff90a7c66b0d4"
        },
        "question": "Test",
        "options": [
            {
                "answer": "answer1",
                "option": "Bob Dylan",
                "votes": 2
            },
            {
                "answer": "answer2",
                "option": "Bob Geldof",
                "votes": 0
            }
    ],
    "options[1]": {
        "votes": 1
    }
}

如您所見,與增加options[1].votes它創建了一個新屬性。

有什么辦法可以通過這樣的變量訪問數組索引?

閱讀有關用於處理數組更新的Positional Operator的信息,

db.collection.update({'_id': questionId, 'options.answer':'answer2'},{"$inc":{"options.$.votes":1}})

而不是做:

var inc = {}; inc["options[" + index + "].votes"] = 1;

你應該做:

var inc = {}; inc["options." + index + ".votes"] = 1;

因此,您不應該使用options[0].votes ,而應該使用options.1.votes ,這就是在MongoDB中完成數組更新的方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM