Ian Mawanda
Ian Mawanda

Reputation: 53

How can I create new fields in return results and set values in them on the basis of conditions using Mongoose?

I have this MongoBD collection called 'Animals'

    [
        {
            _id:ObjectId("5f3ecddd7fe1af0c68614605"),
            status: "wild",
            name: "Wolf"
        },
        {
            _id:ObjectId("5f3ecddd7fe1af0c68614606"),
            status: "domestic",
            name: "Dog"
        },
        {
            _id:ObjectId("5f3ecddd7fe1af0c68614607"),
            status: "domestic",
            name: "Pussy Cat"
        },
        {
            _id:ObjectId("5f3ecddd7fe1af0c68614608"),
            status: "wild",
            name: "Lion"
        },
        {
            _id:ObjectId("5f3ecddd7fe1af0c68614609"),
            status: "wild",
            name: "Snake"
        }
    ]

I want to query that collection using aggregation pipeline in mongoose and return the results with a new field that classifies them according to the status field in the documents. For example, the documents which have status: "wild" get new field new_field: "Tough Forest Animal"

Then the documents which have status: "domestic" get new field new_field: "Friendly Neighborhood Animal"

I want results that look like this

[
    {
        _id: "5f3ecddd7fe1af0c68614605",
        status: "wild",
        name: "Wolf",
        new_field: "Tough Forest Animal"
    },
    {
        _id: "5f3ecddd7fe1af0c68614606",
        status: "domestic",
        name: "Dog",
        new_field: "Friendly Neighborhood Animal"
    },
    {
        _id: "5f3ecddd7fe1af0c68614607",
        status: "domestic",
        name: "Pussy Cat",
        new_field: "Friendly Neighborhood Animal"
    },
    {
        _id: "5f3ecddd7fe1af0c68614608",
        status: "wild",
        name: "Lion",
        new_field: "Tough Forest Animal"
    },
    {
        _id: "5f3ecddd7fe1af0c68614609",
        status: "wild",
        name: "Snake",
        new_field: "Tough Forest Animal"
    }
]

All the help given to me is highly appreciated. Thank you

Upvotes: 1

Views: 38

Answers (1)

Ian Mawanda
Ian Mawanda

Reputation: 53

I finally firgured it out. Use switch statements

AnimalsModel.aggregate([
    {
        $project: {

            "_id": 1,
            "status": 1,
            "name": 1,
            "new_field": {
                "$switch": {
                    "branches": [
                        { "case": { "$eq": [ "$status", "wild" ] }, "then": 'Tough Forest Animal' },
                        { "case": { "$eq": [ "$status", "domestic" ] }, "then": 'Friendly Neighborhood Animal' },
                    ],
                    "default": 'None of the above'
                }
            }
        }
    }
],function (error, animals) {
    console.log(animals)
});

Upvotes: 1

Related Questions