简体   繁体   English

如何在MongoDB中更新数组元素而不是创建新元素

[英]How to update array elements in MongoDB instead of creating new one

I have problem with my code. 我的代码有问题。 I want to update document, which looks like this: 我想更新文档,如下所示:

    {
"_id": {
    "$oid": "5bf2ad5a0d46b81798232cf9"
},
"manufacturer": "VW",
"model": "Golf ",
"VIN": "WVWZZZ1J212566691",
"doors": 3,
"class": "compact",
"reservations": [
    {
        "_id": {
            "$oid": "5bf2ad5a0d46b81798232cfa"
        },
        "pick_up_date": {
            "$date": "2014-10-13T09:13:00.000Z"
        },
        "drop_off_date": {
            "$date": "2014-10-14T09:13:00.000Z"
        },
        "user_id": {
            "$oid": "5bec00bdfb6fc005dcd5423b"
        }
    }
],
"createdAt": {
    "$date": "2018-11-19T12:32:26.665Z"
},
"updatedAt": {
    "$date": "2018-11-19T12:32:26.665Z"
},
"__v": 0
  }

I want to add new reservation to array Reservations. 我想向数组预订中添加新的预订。 My function: 我的功能:

const createReservationForCarId = ({ body , params }, res, next) =>
    Carmodel.findById(params.id)
        .then(notFound(res))
        .then((carmodel) => carmodel ? Object.assign(carmodel, body).save() : null)
        .then((carmodel) => carmodel ? carmodel.view(true) : null)
        .then(success(res))
        .catch(next)

But when I'm trying to update through: 但是当我试图通过更新:

router.put('/:id/reservation',
    createReservationForCarId)

Body: 身体:

{

    "reservations":[

    {

        "pick_up_date" : "October 13, 2017 11:13:00",  
        "drop_off_date": "October 14, 2017 11:13:00",
        "user_id":"5bec00bdfb6fc005dcd5423b"

    }
    ]
}

Mongo instead of update my old document is creating new one with only one reservation gave in above body. Mongo而不是更新我的旧文档,而是在上面的正文中仅保留了一项,而是创建了一个新文档。

What should I do to only update existing document, not creating new one? 我应该怎么做才能仅更新现有文档,而不创建新文档?

I suggest you use $push operator of Mongoose which will append your object to the existing array and it will not create a new one. 我建议您使用Mongoose的$ push运算符,该运算符会将您的对象附加到现有数组中,并且不会创建新数组。

Check out this link:- https://github.com/Automattic/mongoose/issues/4338 查看此链接: -https : //github.com/Automattic/mongoose/issues/4338

You can try the findAndModify instead of findById in your code. 您可以在代码中尝试使用findAndModify而不是findById Check out the syntax here 这里查看语法

I haven't used mongoose but they have documentation for array manipulation. 我没有用过猫鼬,但是他们有关于数组操作的文档。

See here: https://mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-push 看到这里: https : //mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-push

Also here is the related mongo doc for array manipulation: https://docs.mongodb.com/manual/reference/operator/update/push/ 这也是用于数组操作的相关mongo文档: https : //docs.mongodb.com/manual/reference/operator/update/push/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM