2017-02-18 174 views
0

我已將mongoose與我的應用程序一起使用,並嘗試檢索具有國家/地區類型和採用其元數據字段的文檔。按字段篩選並選擇另一個字段mongodb

我的文檔看起來如下,

enter image description here

我有代碼,

dbHelper.query(mongoose.model('_entity'), { 
       'type': 'country' 
      }, function (error, data) {     
       callback(data); 
      }); 

dbHelper:

query: function (model, conditon, options) { 
      return new Promise(function (resolve, reject) { 
       options = options || {}; 
       model.find(conditon, {}, options, function (error, data) { 
        if (error) 
         console.log("error is"+err); 
         reject(error); 
        console.log("data is "+data); 
        resolve(data); 
       }) 
      }) 
     } 

這個應該怎麼才能變爲選擇metadata字段?

回答

1

你可以改變你find查詢了一下,只選擇metada或任何fields你想要的。

model.find(conditon, {"metadata" : 1}, options, function (error, data) { 
    if (error) 
     console.log("error is"+err); 
     reject(error); 
    console.log("data is "+data); 
    resolve(data); 
}); 

如果無法在現有的find查詢中添加元數據,則可以嘗試替代方法。

將另一個參數projection添加到查詢函數中。

query: function (model, conditon, projection, options) { 
    return new Promise(function (resolve, reject) { 
     options = options || {}; 
     projection = projection || {}; 
     model.find(conditon, projection, options, function (error, data) { 
      if (error) 
       console.log("error is"+err); 
       reject(error); 
      console.log("data is "+data); 
      resolve(data); 
     }) 
    }) 
} 

而且使用這樣的:

dbHelper.query(mongoose.model('_entity'), { 
    'type': 'country' 
},{ 
    'metadata' : 1//add other required fields if needed 
}, function (error, data) {     
    callback(data); 
}); 

我認爲這會在你的情況下工作。

1

您需要select

mongoose 
    .model('_entity') 
    .find() 
    .where('type').equals('country') 
    .select('metadata') 
    .exec(function(error, data) { 
     callback(data); 
    }); 

更新:例如projection = ["metadata", "name"]

query: function (model, conditon, projection, options) { 
      return new Promise(function (resolve, reject) { 
       options = options || {}; 
       projection = projection || []; 
       model.find(conditon, projection.join(" "), options, function (error, data) { 
        if (error) 
         console.log("error is"+err); 
         reject(error); 
        console.log("data is "+data); 
        resolve(data); 
       }) 
      }) 
     } 
+0

我知道我們需要選擇,但我如何修改上述代碼? – Sajeetharan

+0

@Sajeetharan「投影」呢? –

+0

現在該如何調用此查詢?條件將爲空 – Sajeetharan

相關問題