首页 > 解决方案 > 如果现有数组中列出了另一个属性,如何在 Mongoose 中投影一个新的布尔字段?

问题描述

考虑 Mongoose 中的查询:

  let StudentCodes = .... // getting this from somewhere


  await Students.aggregate(
    [

      {
        $project: {
          StudentCODE: "$StudentCODE",
          StudName: "$StudName",
          StudProfileDesc: "$StudProfileDesc",
          IsReviewed: {
            $cond: [{ $eq: [StudentCodes, "$StudentCODE"] }, 1, 0]
          }
        }
      }
    ],
    function(err, results) {
      if (err) {
        console.log(err);
      }
      console.log(results);
      return res.status(200).json(results);
    }
  );

如果属性存在于数组中,IsReviewed我们如何进行投影truefalseStudentCODEStudentCodes

标签: node.jsmongodbmongoose

解决方案


尝试如下,您可以使用$in in$cond来做到这一点:

let StudentCodes = .... // getting this from somewhere


    await Students.aggregate(
        [

            {
                $project: {
                    StudentCODE: "$StudentCODE",
                    StudName: "$StudName",
                    StudProfileDesc: "$StudProfileDesc",
                    IsReviewed: {
                        $cond: [{ $in: ["$StudentCODE", StudentCodes] }, true, false]
                    }
                }
            }
        ],
        function (err, results) {
            if (err) {
                console.log(err);
            }
            console.log(results);
            return res.status(200).json(results);
        }
    );

推荐阅读