首页 > 解决方案 > Mongodb, nodejs: find an object and update its value

问题描述

I am struggling to find a solution to update client's data to the database. I have a document looking like this:

{
  "_id": {
    "$oid": "60249fccf992b73b340c7c94"
  },
  "username": "john",
  "inv": {
    "id01": {
      "n": "Apple",
      "r": "0"
    },
    "id02": {
      "n": "Pear",
      "r": "0"
    },
    "id03": {
      "n": "Pear",
      "r": "0"
    },
    "id04": {
      "n": "GreenApple",
      "r": "0"
    }
  }
}

and this is the json data sent from the client

{
  "id02": {
    "n": "Pear",
    "r": "1",
    "z": "-1.0001",
    "x": "-2.34",
    "y": "-2.41"
  },
  "id03": {
    "n": "Pear",
    "r": "1",
    "z": "-1.0002",
    "x": "-0.52",
    "y": "-2.41"
  }
}

I want to look for the objects from the json data sent by client in the database (for instance: "id02") and update its value. I am pretty new to Mongodb so I am struggling with finding the proper technique to do so.

The document should be looking like this

{
  "_id": {
    "$oid": "60249fccf992b73b340c7c94"
  },
  "username": "john",
  "inv": {
    "id01": {
      "n": "Apple",
      "r": "0"
    },
   "id02": {
    "n": "Pear",
    "r": "1",
    "z": "-1.0001",
    "x": "-2.34",
    "y": "-2.41"
  },
  "id03": {
    "n": "Pear",
    "r": "1",
    "z": "-1.0002",
    "x": "-0.52",
    "y": "-2.41"
  },
    "id04": {
      "n": "GreenApple",
      "r": "0"
    }
  }
}

I try this but it replaces everything in the "inv" with the new data

   var addToSet = {};
    for(var key in data)
     {
    addToSet[key] = data[key];
     }
     db.get().collection('userdata').updateOne({ username: ws.userId},{'$set': {'inv':addToSet}})

标签: node.jsmongodb

解决方案



  1. 我用这个: const Product = require(Path Model Moongose);

常量数据 = {

            NameProducts: req.body.title,
            TitleProducts: req.body.body,
            PriceProducts: req.body.price,
            TagesProducts: req.body.tags
};
      
        await Product.updateOne({ _id: Find with your idea  }, { $set: data });

推荐阅读