检查对象ID是否在对象ID数组中

时间:2020-11-09 18:29:39

标签: node.js mongodb mongoose

我正在尝试检查登录的用户ID req.user.id.是否在req.params.id被检查用户的关注者数组中,出于某种原因,它没有工作。

router.get('/api/:id/isfollowing', auth, async (req, res) => {

    if (req.params.id==req.user._id) {
        return res.status(200).send({ "isfollowing": "Myself" })
    }

    try {
        const followers = await Follow.find({
            user: req.params.id
        })

        let followersArr = followers.map(follower=>{
            return follower.followedBy
        })

        const yes = followersArr.includes(req.user._id)
        // const yes = followersArr.filter((objId) => objId==req.user._id)

        console.log(yes, followersArr, req.user._id)

        if (yes===false) {
            return res.status(200).send({ "isfollowing": false })
        }

        return res.status(200).send({ "isfollowing": true })

    } catch (e) {
        res.status(500).send()
    }
})

由于某种原因,该检查不起作用,即使使用过滤器,它仍然不返回任何内容。但是当我console.log的值,它就在那里。

[] [ 5fa4f0af4a7bf5471c41e225, 5f9dc1777a695570e878424d ] 5f9dc1777a695570e878424d

编辑 下面的模式

用户架构

const userSchema = new mongoose.Schema({
    fullname: {
        type: String, 
        required: true,
        trim: true,
        lowercase: true
    },
    username: {
        type: String,
        unique: true,
        required: true,
        trim: true,
        lowercase: true
    },
    email: {
        type: String,
        unique: true,
        required: true,
        trim: true,
        lowercase: true,
        validate(value) {
            if (!validator.isEmail(value)) {
                throw new Error('Email is invalid')
            }
        }
    },
    password: {
        type: String,
        required: true,
        minlength: 7,
        trim: true,
        validate(value) {
            if (value.toLowerCase().includes('password')) {
                throw new Error('Passwoed cannot contain "password"')
            }
        }
    }
})

遵循模式

const followSchema = new mongoose.Schema({
    // the logged in user who will be trying to follow someone will be added to "followedBy"
    // the user who is getting followed will be added to "user"
    user: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
    followedBy: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'Showcase'
    }
}, {
    timestamps: true
})

我给出了自己的模式,因此我可以记录其他信息,例如时间和每当用户跟随​​另一个用户时的其他信息。

2 个答案:

答案 0 :(得分:1)

如果我很了解,您只需要一个简单的查询即可。

由于您只想知道id是否放入数组,因此可以直接使用mongo进行检查。您不需要将每个文档都加载到内存中并使用JS之类的filter函数或类似的函数。

您只需要类似以下查询:

db.collection.find({
  "user": ObjectId("user_id"),
  "followedBy": ObjectId("follower_id")
})

这将返回匹配两个值的文档。

检查here是否有效,并告诉我您期望的行为和输出是什么。

我还将编写一个mongoose查询,并更新答案。

您也可以在mongoose中使用此查询来获取有多少文档找到该查询:

var find = await model.find({"user":mongoose.Types.ObjectId(user_id),"followedBy":mongoose.Types.ObjectId(follower_id)}).countDocuments()

答案 1 :(得分:0)

在这种情况下不能使用包含,因为您试图在数组中查找ObjectId。

要查找followersArr中是否存在req.user._id,请使用以下Array.some()函数

const yes = followersArr.some(followerId=>{followerId.equals(req.user._id)})

some调用将遍历followersArr数组,对每个调用equals以查看其是否与req.user._id相匹配,并在找到匹配项后立即停止。如果找到匹配项,则返回true,否则返回false。

不能使用像indexOf这样的简单对象,因为您想按值而不是按引用比较ObjectID。