Mongodb coalesce equivalent (with mongoose)

I have a localization where each document is a pair of key values ​​translated into several languages.

This is a JSON view:

[
  { "_id": "form.password" , "en": "Password"  , "he": "סיסמא"  , "ru": "" }
  { "_id": "form.email"    , "en": "Email"     , "he": "אימייל" },
  { "_id": "form.firstname", "en": "First Name", "he": "שם פרטי", "ru": "" }
]

This is a mongoose diagram:

new Schema({
  _id: {
    type: String,
    required: true
  },
  en: String,
  he: String,
  ru: String
});

I need to get all key values ​​in each language using express.js:

app.get('/api/locals', function(req, res) {
  Local.find().select( req.query.language ).exec(function(err, data) {
    res.json(data);
  });
});

This works fine , if each language has values ​​for all keys , but I want to make a backup , if any language does not matter for a specific key, then the English value will be used.

I thought maybe I should use aggregation or mapReduce, but I don't know how to implement this using mongoose.

With SQL, I used to write this query:

SELECT key, COALESCE($language , en) as value FROM locals

Thanks in advance.

+4
1

:

$project $IFNULL:

app.get('/api/locals', function(req, res) {
  Local.aggregate({
    $project: {
      value: {
        $ifNull: ["$" + req.query.language , "$en"]
      }
    }
  }).exec(function(err, data) {
    res.json(data);
  });
});
+6

Source: https://habr.com/ru/post/1524943/


All Articles