mongoose 比较数组中是否已存在ObjecticID

idfiyjo8  于 2023-02-19  发布在  Go
关注(0)|答案(2)|浏览(99)

在mongo上,我为每个user创建了history列数组,以获取特定卡的ID,因此我想设置一个是否知道的条件:

要理解我的代码:

  • 找到ID用户,找到他的history:如果卡ID已经存在=〉不要在该数组上复制ID
  • 但是,如果不存在:将ID添加到他自己的history数组中。

My req.body._id是用户提交的Id

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);
  }
}

我得到这个错误:

ERROR  Expression $in takes exactly 2 arguments. 1 were passed in.

谢谢

31moq8wy

31moq8wy1#

只是尝试在数组中使用它。const ids = [req.body._id];const condition = await User.find(forThisUser, {"history" : { $in : [ids]}})这里是官方链接,说你必须使用$in : [array]https://mongoosejs.com/docs/api/aggregate.html

p3rjfoxz

p3rjfoxz2#

请参考Monngoose的文档:
您的查询应该是:

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

Find将filters参数作为对象,该对象为:

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

与您的问题无关,但您可能也想看看您的HTTP response codes
例如,对于重复的条目,您将返回409 Conflict,或者返回400 Bad Request而不是401 Unauthorized
如果添加了卡,则可以返回200 Success204 No Conntent,除非您在同一请求中创建卡资源,否则将返回201 Created

相关问题