Search code examples
mongoose

How to find _id and verify if it has an existing key in mongoose please?


I want to find user by its _id and verify if he had or not btc in his wallet?

users =
{
  "_id": "6515a3cb181eafcdd26460ce"
  "wallet": [
    {
      "btc": 0.1
    },
    {
      "bnb": 20
    }
  ]
}

I try this

const id = "6515a3cb181eafcdd26460ce"
const query = await users.findOne({ _id: id, wallet: {$in: [`btc`]} });

Solution

  • I'm not sure how your documents will be stored in terms of the btc object but this will cover you just in case the value of btc is zero ("btc": 0) or if the btc property is not there.

    This will match if all conditions are true:

    1. The _id is a match
    2. The document has an object in the wallet array with a key btc that is not null
    3. The document has an object in the wallet array with a key btc that is not equal to zero.
    const id = "6515a3cb181eafcdd26460ce" 
    const query = await users.findOne({
      _id: id,
      wallet: {
        $elemMatch: {
          $and: [
            {
              btc: {
                $ne: 0
              }
            },
            {
              btc: {
                $ne: null
              }
            }
          ]
        }
      }
    });
    

    See it working here. You will notice I have included a few different objects. One without the an object containing btc, one with a "btc":0, and one with a "btc":null.

    Edit: If you want to update the value then you can increment the btc value using $inc and then check that the update was successful. The findOneAndUpdate method returns null if no document was found so you will know if it was unsuccessful. I have included the code below to get you started:

    try {
       const user = await users.findOneAndUpdate({ _id: "6515a3cb181eafcdd26460ce",
         wallet: {
           $elemMatch: {
             $and: [
               {
                 btc: {
                   $ne: 0
                 }
               },
               {
                 btc: {
                   $ne: null
                 }
               }
             ]
           }
         }
       }, { $inc: {"wallet.$.btc": 0.5 }}, {new: true});
    
       if(!user){ //If null
          // No user found, update not successful
          // Respond to front-end
       }else{
          // Repond to front-end with success
       }
    }catch(err){
       console.log(err);
       //Handle error response to front-end
    }