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`]} });
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:
_id
is a matchbtc
that is not null
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
}