簡體   English   中英

ZCCADDEDB567ABAE643E15DCF0974E503Z:如果數組中不存在條目,則返回 boolean 變量

[英]Mongoose: return a boolean variable if entry not present in array

我可以根據 mongoose 查詢中的條件返回 boolean 變量嗎? 例如,在獲取用戶的所有通知時,我想顯示用戶是否看到通知。

我有這個架構:

const notificationSchema = mongoose.Schema({
    userid: { type: mongoose.Schema.Types.ObjectId, ref:'User', require: true, unique: false },
    time: Number,
    type: Number,
    seenBy: {type: [String], default: []}      // can have very large number of values (user IDs)
}, {__v: false});

現在,在獲取通知數組時,我想獲得一個額外的字段,如果特定用戶存在於該字段的各個seen [] 數組中,則該字段為真。 這樣我得到響應 object 就像 1 個新通知[{userid: <someid>, time: ... <other fields>..., seen: false}]

謝謝

您將必須運行一個聚合操作,其中您在兩個 arrays 即[userId]和 seenBy arrays 上使用$setIsSubset運算符,當第一個數組是第二個數組的子集時返回 true,包括當第一個數組等於第二個數組時,否則為假。

第一個 userid 數組應該是一個字符串數組,因為您將該數組與另一個字符串類型的數組進行比較,因此您需要使用$toString將 ObjectId 轉換為字符串。

例如,以下顯示了查詢:

const userId = '5ffafefe288e7a58ff08226e'; // the user id input variable as a string, could be from req.params.id or req.query.userId etc
const notifications = await Notification.aggregate([
    { '$match': { userid: mongoose.Types.ObjectId(userId) } },
    { '$addFields': { 
        'seen': {
            '$setIsSubset': [
                [{ '$toString': '$userid' }],
                '$seenBy'
            ]
        }
    }}
]);

你應該試試

async func () {
    const doesUserExit = await User.exists({ _id: userid });
}

閱讀更多model.exists ,將返回真或假。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM