Push items into mongo array via mongoose

前端 未结 8 1593
小鲜肉
小鲜肉 2020-11-22 03:22

I\'ve scoured SO a good bit looking for the answer but I\'m sure that I\'m lost for the right words to describe what I\'m after.

Basically I have a mongodb collection

8条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 04:27

    Use $push to update document and insert new value inside an array.

    find:

    db.getCollection('noti').find({})
    

    result for find:

    {
        "_id" : ObjectId("5bc061f05a4c0511a9252e88"),
        "count" : 1.0,
        "color" : "green",
        "icon" : "circle",
        "graph" : [ 
            {
                "date" : ISODate("2018-10-24T08:55:13.331Z"),
                "count" : 2.0
            }
        ],
        "name" : "online visitor",
        "read" : false,
        "date" : ISODate("2018-10-12T08:57:20.853Z"),
        "__v" : 0.0
    }
    

    update:

    db.getCollection('noti').findOneAndUpdate(
       { _id: ObjectId("5bc061f05a4c0511a9252e88") }, 
       { $push: { 
                 graph: {
                   "date" : ISODate("2018-10-24T08:55:13.331Z"),
                   "count" : 3.0
                   }  
               } 
       })
    

    result for update:

    {
        "_id" : ObjectId("5bc061f05a4c0511a9252e88"),
        "count" : 1.0,
        "color" : "green",
        "icon" : "circle",
        "graph" : [ 
            {
                "date" : ISODate("2018-10-24T08:55:13.331Z"),
                "count" : 2.0
            }, 
            {
                "date" : ISODate("2018-10-24T08:55:13.331Z"),
                "count" : 3.0
            }
        ],
        "name" : "online visitor",
        "read" : false,
        "date" : ISODate("2018-10-12T08:57:20.853Z"),
        "__v" : 0.0
    }
    

提交回复
热议问题