javascript – How do I make a query in Mongo?

Question:

I have the following schema structure

 var ArticleSchema = new Schema({
      created: {
         type: Date,
         default: Date.now
                },
       title: {
          ru : {
             type: String,
             default: '',
             trim: true,
             required: 'Заголовок должен быть заполнен'
               },
          en : {
             type: String,
             default: '',
             trim: true,
             required: 'Title cannot be blank'
                }
          },
        content: {
          ru : {
             type: String,
             default: '',
             trim: true,
             required: 'Текст должен быть заполнен'
              },
          en : {
            type: String,
            default: '',
            trim: true,
            required: 'Title cannot be blank'
               }
             },
          user: {
            type: Schema.ObjectId,
            ref: 'User'
                }
 });

And I want to receive title and content depending on the existing locale. I get it using the getLocale() method from i18n. How can a request be made in a controller

 exports.list = function (req, res) {
   var locale = i18n.getLocale()// выдаёт правильно - en или ru
   var query = {{'title.locale':{ $exists : true, $ne : null }} // Вот что сюда воткнуть???
     Article.find().sort('-   created').populate('user', 'displayName').exec(function (err, articles) {

    if (err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
      });

  } else {
     res.json(articles);
  }
 });
};

to get title and content only in the required language?

Answer:

The catch is not in the choice of documents – find(query) , but in the fields you want to get – select(projection) . Form a projection based on the current locale

var locale="ru", //или "en"
    projection = {"created":true,"user":true};
projection['title.'+locale]=true;
projection['content.'+locale]=true;
//projection = {created:true, user:true, title.ru:true, content.ru:true}
//и в найденных документах будут указаны только перечисленные поля
Article.find().select(projection).sort...//дальше ваш код
Scroll to Top