In mongo, I made history
column array for each user
to get the Id of specific card, so I would like to made a condition or not for knowing that :
To understand my code :
-
find the ID user, find his
history
:
if card ID already present => don’t duplicate ID on this array -
but, if is not present :
add the ID on his ownhistory
array.
My req.body._id
is the Id
value who the user submit
const forThisUser = { _id: req.user._id }
const condition = await User.find(forThisUser, {"history" : { $in : req.body._id}})
async function alreadyPresentOrNot(res, req){
if(condition>0){
console.log("Already present !")
res.sendStatus(401);
}
else{
console.log("Card not finding, add on array now !")
await User.findOneAndUpdate(forThisUser, { $addToSet: { history: req.body._id } }, {upsert: true})
res.sendStatus(201);
}
}
I got this error :
ERROR Expression $in takes exactly 2 arguments. 1 were passed in.
Thanks
2
Answers
Please refer to Monngoose’s documentation:
Your query should be:
Find takes the filters argument as an object, which would be:
Unrelated to your question, but you may want to have a look at your HTTP response codes as well.
For example, for a duplicated entry you would return a
409 Conflict
, or a400 Bad Request
not a401 Unauthorized
.And if the card is added you can return
200 Success
or204 No Conntent
, unless you are creating the card resource in that same request your return201 Created
Just try using it in an array.
const ids = [req.body._id];
const condition = await User.find(forThisUser, {"history" : { $in : [ids]}})
Here is the official link that says you have to use
$in : [array]
https://mongoosejs.com/docs/api/aggregate.html?