如果我的用戶架構如下所示
const user = new schema(
Id: {
type: ObjectId,
},
followers: {
type: Array,
default: [],
},
)
我想迭代跟隨者陣列并根據陣列中存在的搜索 ID 回傳一個布林值 true 或 false。
例如:如果我有一個檔案用戶 ID:123,并且用戶 ID 為 234 的用戶正在關注 ID 為 123 的用戶。所以 123 的檔案看起來像這樣:
{
Id: 123,
followers:[234,356,....]
}
應該構造什么查詢,以便存在追隨者陣列的迭代,并且如果請求引數(req.params.id)中的值(req.body.userId)存在,則查詢回傳true,否則回傳false
const User = require("../models/users");
router.put("/followuser/:id", async (req, res) => {
if (req.params.id !==req.body.userId){
const followed = await User.exists(/*code to check if 234(req.body.userId) is present in the followers array*/)
if(followed == true) {
// further code to allow following the user
}else {
res.status(400).json("You Already follow the user")
}
}else {
res.status(400).json("Cannot follow yourself mate")
}
} )
uj5u.com熱心網友回復:
有很多方法可以做到這一點,希望這個查詢可以適應您的目的。
db.users.find(
{ "Id": 123 }, // <-- this user's ID
{
"_id": 0,
"present": { "$in": [ 234, "$followers" ] }
}) // ^
// Is this ID already a follower?
在mongoplayground.net上試試。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/489432.html
上一篇:查詢陣列中每個元素的貓鼬
