如何检索mongodb文档,然后检查objectIds数组是否包含值

时间:2019-02-12 01:16:43

标签: javascript node.js mongoose

我具有以下功能

exports.createRequest = async (req, res) => {

  const currUser = await User.findById(req.user._id)
    .catch(err => console.log(err))

  const friends = currUser.friends

  console.log(friends)

  const requestedId = mongoose.Types.ObjectId(req.params.id)

  if (friends.includes(requestedId)) {

    return res.status(400).send('You\'re already friends')

  }

  ...

}

和以下模型:

const UserSchema = new Schema({
  ...

  friends: [{ type: Schema.Types.ObjectId, ref: 'User' }]
})

在数据库内部,“ friends”字段是ObjectId数组(按预期)

{
  friends: [ 000000483d6b4e132a0feb18, 5c62222b3d6b4e132a0feb17 ]
  _id: 5c62222b3d6b4e132a0feb16
}

但是当我将'friends'常量(currUser.friends)登录到控制台时,我得到了:

["000000483d6b4e132a0feb18","5c62222b3d6b4e132a0feb17"]

这意味着我的include()函数无法正常工作,因为它试图在字符串数组中查找ObjectId。

当我登录currUser.friends [0]时,我再次获得一个ObjectId ...

000000483d6b4e132a0feb18

有人知道更好的方法吗?我已经尝试过将req.params.id强制转换为字符串无效。

我知道我可以在查找查询中包括朋友,但是我有很多类似的字段,因此效率低下。

0 个答案:

没有答案