skip to Main Content

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 :

enter image description here

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 own history 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


  1. Please refer to Monngoose’s documentation:

    Your query should be:

    const forThisUser = { _id: req.user._id }
    const condition = await User.find({...forThisUser, "history" : { $in : req.body._id}})
    

    Find takes the filters argument as an object, which would be:

    { 
      _id: req.user._id,
      history: { $in: req.body._id } 
    }
    

    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 a 400 Bad Request not a 401 Unauthorized.

    And if the card is added you can return 200 Success or 204 No Conntent, unless you are creating the card resource in that same request your return 201 Created

    Login or Signup to reply.
  2. 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?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search