Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expressjs: res.json removes the empty subdocument of mongoose result

My Schema is as follows:

var MySchema = new mongoose.Schema({
    userEmail: {
        type: String,
        trim: true
    },
    subscription: {}
});

I have a document like this:

{
    "_id" : ObjectId("565c16d3951a55934acaca75"),
    "userEmail" : "[email protected]",
    "subscription" : {
        "project1" : {
            "subproject1" : [ 
                "comp1"
            ]
        },
        "project2" : {}
    }
}

Using mongoose, if I try this:

router.post('/getApi', function(req, res, next) {
    MyModel.findOne(
        {
            userEmail: "[email protected]"
        }, function(err, data) {
            if (err) return next(err);
            res.json(data);
        }
    );
});

I'm getting output as:

{
    "_id" : ObjectId("565c16d3951a55934acaca75"),
    "userEmail" : "[email protected]",
    "subscription" : {
        "project1" : {
            "subproject1" : [ 
                "comp1"
            ]
        }
    }
}

The project2 is removed since it has empty document. If I try in mongo console, I'm not facing this issue.

I suspect issue in res.json() method. Because when console.log(data), I'm getting what I expected. Kindly share your views.

like image 958
Vimalraj Selvam Avatar asked Dec 13 '25 20:12

Vimalraj Selvam


1 Answers

Found a solution. We have to set minimize option to false as part of our Schema definition. The documentation says: mongoose minimize option. I had it to set it false.

So my schema becomes:

var MySchema = new mongoose.Schema({
    userEmail: {
        type: String,
        trim: true
    },
    subscription: {}
}, {minimize: false});

And this solved my problem.

like image 67
Vimalraj Selvam Avatar answered Dec 15 '25 12:12

Vimalraj Selvam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!