Augustin Riedinger
Augustin Riedinger

Reputation: 22270

Mongoose model select query with empty fields present

When I write:

User.find({}).select('email firstName lastName').exec(...)

I'd expect the resulting user to have the following structure:

{
  email: '[email protected]',
  firstName: null,
  lastName: null
}

even if firstName and lastName aren't set for this record. Instead I get:

{
  email: '[email protected]'
}

Is there a way to achieve what I want?

Upvotes: 0

Views: 814

Answers (1)

Oleks
Oleks

Reputation: 1633

As was mentioned in the comment, you can achieve that result with help of aggregation and $ifNull operator. In mongoose it will look like:

User.aggregate(
    [
        {$project: {
            _id:0,
            email: {$ifNull: ["$email", null]},
            firstName: {$ifNull: ["$firstName", null]},
            lastName: {$ifNull: ["$lastName", null]}
        }}
    ],
    function(err,result) {
        // Result is an array of documents
    }
)

Upvotes: 1

Related Questions