MongoJS添加到现有阵列

时间:2015-11-01 09:44:12

标签: javascript arrays node.js mongodb mongojs

我正在尝试添加到mongoDB中的现有数组。这是我所拥有的,但它当然是不正确的,因为所有数据在尝试添加后都会被删除:

db.cardKeeper.update(
        {_id: ObjectId('5621c5ac30895e5776e4d1ea')},
        {
            $push:{'cardKeeperApp.appData.cardDecks':deckObject}
        }
    )

deckObject这是我试图添加到数组的对象,如下所示

var deckObject = {
        name: productName,
        searchName: productItem,
        price:{
            purchasePrice: productCost,
            averageWorth: priceAverageFixed,
            lowWorth: lowestSoldAmount,
            highWorth: highestSoldAmount
        }
    }

正如您所见,cardKeeperApp.appData.cardDecks是我的数组,其中包含更多信息,看起来就像deckObject

如果有帮助,这里是完整的对象,我试图添加到cardDecks数组。我将字段标记为空

{
    "_id" : ObjectId("5635ddf82f4c220f4f932af2"),
    "cardKeeperApp" : {
        "appData" : {
            "cardDecks" : [
                {
                    "name" : "Some Name",
                    "searchName" : "Some+Name",
                    "price" : {
                        "purchasePrice" : null,
                        "averageWorth" : null,
                        "lowWorth" : null,
                        "highWorth" : null
                    }
                }
            ],
            "allDeckTotalWorth" : null
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。 findAndModify query:{_id:ObjectId}然后更新并推送:

db.cardKeeper.findAndModify({query:{_id: ObjectId('5635ddf82f4c220f4f932af2')},
    update: {$push:{'cardKeeperApp.appData.cardDecks': deckObject}},
    new:true}, function (err, doc) {
        res.json(doc);
    });