MongoDB: how to update only one element in the document?

谁说胖子不能爱 提交于 2021-01-29 09:14:23

问题


I want to updates only one element in the document to use put request

I tried

PUT localhost:3000/api/memo/5b8e382d61984255d879f872

{
    text: "updated!"
{

but, it updated like this

{
    text: "updated!",
    imgUrl: null,
    tag: null,
    ...
}

Is there a way to updates one element in document?

await Memo.where('_id')
      .equals(req.params.id)
      .updateOne({
        imgUrl: req.body.imgUrl,
        text: req.body.text,
        tag: req.body.tag,
        user: req.body.user,
        loc: req.body.loc
      })

回答1:


You can use the following solution to update only one element:

Memo.updateOne(
  { "_id" : ObjectId("5b8e83957d56e802274d6") },
  { $set: { "text" : "updated" } });

UpdateOne() updates the first matching document in the collection that matches the filter.The above query operation updates a single document where text: "updated".

The operation can either replace an existing document or update specific fields in an existing document.



来源:https://stackoverflow.com/questions/52165805/mongodb-how-to-update-only-one-element-in-the-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!