2012-03-03 344 views
24

我很困惑與使用select方法。這是我如何使用它,這是錯誤的:Mongoose使用.select()方法

Transaction.find({username : user.username}).select('uniqueId', 'confirmation_link', 'item_name', 'timeout', 'username', function(err, txs){ 
     callback(txs); 
}); 

我試圖做到的,是單純從交易數據庫中選擇與用戶名的人,我要拿出剛剛上市的領域在select方法中。任何人都可以指出我應該如何使用select方法?謝謝。

回答

45

docs說,你可以像這樣實現:

貓鼬V4.0

// Retrieving only certain fields 

Model.find({}, 'first last', function (err, docs) { 

}); 

老過時的API

// Retrieving only certain fields 

Model.find({}, ['first', 'last'], function (err, docs) { 
    // docs is an array of partially-`init`d documents 
    // defaults are still applied and will be "populated" 
}); 

這樣你就可以做到這一點沒有select()

+2

看來這種方法正在工作,但仍然在'文檔'我最終有'_id',我不想有的領域。 – Masiar 2012-03-04 10:22:15

+1

除'_id'之外的任何其他字段您都不要求?如果沒有,我會認爲'_id'是一個例外,因此總是返回...但這只是一個猜測 – pkyeck 2012-03-04 23:03:54

+0

實際上所有的字段都是除了'_id'字段之外的所有字段。我不想要它。有沒有辦法避免這種情況? – Masiar 2012-03-05 14:40:52

8

這是另一種方式:queries in mongoose

Transaction.find({username : user.username}) 
.select('uniqueId confirmation_link item_name timeout username') 
.exec(function(err, txs) { 
     console.log(txs); 
}); 
+0

適合我,謝謝@lee – 2015-09-12 19:28:39

+1

好一,你還應該添加如何排除字段 – 2015-11-24 02:04:56

3

要只提取特定的字段,請使用下,

Model.find({/*Your query*/}, {'firstName':1, 'lastname':1, '_id':0}, //Notice, this will omit _id! function (err, docs){}.....

,將工作,不會在任何額外的ID帶來如_id 。

17

現在有這樣做(不使用.select和不使用的陣列),只是傳遞字段單獨用空格作爲第二個參數

User.find({}, 'first last', function (err, usr) { 
    //Got the result, saved a few bytes of code 
}); 

The Docs

5

要檢索某些的較短路字段而不檢索可指定排除它的'_id'

Model.find({}, {'Username':1, '_id':0}, function (err, docs){}..... 
1

選擇&投影可以在nodejs中以這種方式輕鬆完成操作。試試這個

相關問題