简体   繁体   中英

How to filter nested object property to update a document in Express and MongoDB?

I want to filter the email to change the JSON file. I can not filter the nested property of the object. How to do that.

app.put("/users/:email", async (req, res) => {
          const email = req.params.email;
          //console.log(email);
          **const filter = { email: email };**
          const result = await userCollection.updateOne(filter, {
            $set: { value: "00" },
          });
          res.json(result);
        });

A JSON document from MongoDB:

[
  { "firstName" : "John",  
    "lastName"  : "Doe",
    "age"       : 23,
    "info"      : {"userID": 3434, "email": "test@test.com", "value": 35}
   },

  { "firstName" : "Mary",  
    "lastName"  : "Smith",
     "age"      : 32,
    "info"      : {"userID": 343, "email": "test2@test.com", "value": 65} }
]    
         

How to filter the email from the JSON file? So I can update the value by filtering the email.

You must create a filter with a nested field like this:

const filter = { "info.email": email };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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