Aggregate query runs in mongodb and not in mongoose

user2285831

I have a collection myCollection with array of members and number of places:

{
   name : String,
   members: [{status : Number, memberId : {type: Schema.Types.ObjectId, ref: 'members'}],
   nbPlaces : Number
}

and i have this data

"_id" : ObjectId("5e83791eb49ab07a48e0282b")
   "members" : [ 
        {
            "status" : 1,
            "_id" : ObjectId("5e83791eb49ab07a48e0282c"),
            "memberId" : ObjectId("5e7dbf5b257e6b18a62f2da9")
        }, 
        {
            "status" : 2,
            "_id" : ObjectId("5e837944b49ab07a48e0282d"),
            "memberId" : ObjectId("5e7de2dbe027f43adf678db8")
        }
    ],
  "nbPlaces": 5

I make a $match with field added by $addFields, but this returns results in mongoDb and not in mongoose, How can I get results in mongoose ? thank you.

mongoose version : ^5.9.4"

myCollection.aggregate([
  {
    $project: {
      nbMembers: {
        $size: {
          $filter: {
            input: "$members",
            as: "member",
            cond: { $eq: ["$$member.status", 1] },
          },
        },
      },

      nbPlaces: 1,
    },
  },
  {
    $addFields: {
      charged: {
        $cond: {
          if: { $eq: [{ $subtract: ["$nbPlaces", "$nbMembers"] }, 0] },
          then: true,
          else: false,
        },
      },
    },
  },
  { $match: { _id: ObjectId("5e83791eb49ab07a48e0282b"), charged: false } },
]);
SuleymanSah

I can get the result with mongoose like this:

const mongoose = require("mongoose");
const ObjectId = mongoose.Types.ObjectId;

router.get("/test", async (req, res) => {
  const result = await myCollection.aggregate([
    {
      $project: {
        nbMembers: {
          $size: {
            $filter: {
              input: "$members",
              as: "member",
              cond: { $eq: ["$$member.status", 1] },
            },
          },
        },
        nbPlaces: 1,
      },
    },
    {
      $addFields: {
        charged: {
          $cond: {
            if: { $eq: [{ $subtract: ["$nbPlaces", "$nbMembers"] }, 0] },
            then: true,
            else: false,
          },
        },
      },
    },
    { $match: { _id: ObjectId("5e83791eb49ab07a48e0282b"), charged: false } },
  ]);

  res.send(result);
});

Which gives this result:

[
    {
        "_id": "5e83791eb49ab07a48e0282b",
        "nbPlaces": 5,
        "nbMembers": 1,
        "charged": false
    }
]

Please check if your myCollection schema matches your data, I used this:

const mongoose = require("mongoose");

const schema = new mongoose.Schema({
  name: String,
  members: [
    {
      status: Number,
      memberId: { type: mongoose.Schema.Types.ObjectId, ref: "members" },
    },
  ],
  nbPlaces: Number,
});

module.exports = mongoose.model("myCollection", schema);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related