Search code examples
node.jsmongoose

Retrieving the first letter of firstname in mongoose


I have to following line of code in my Mongoose query which is retrieving the full name of the user in a name field:

populate("reviews.userid",{name:{$concat:["$firstname"," ","$lastname"]}})

How could I extend this to retrieve the first letter of the firstname only, followed by a dot and then the full last name?

E.g. for Mary Khan, I want to retrieve M. Khan


Solution

  • $substr has been deprecated since version 3.4. You can use $substrCP operator to extract first character of the firstname with $toUpper to capitalize it.

    populate("reviews.userid", {
      name: {
        $concat: [
          { $toUpper: { $substrCP: ["$firstname", 0, 1] } },
          ". ",
          "$lastname"
        ]
      }
    })
    

    You can read more about $substrCP at https://www.mongodb.com/docs/manual/reference/operator/aggregation/substrCP/