2012-03-07 74 views
25

我想從我的Node.js應用程序中的Mongoose設置檢索一些數據。我注意到無論我作爲字段選擇寫什麼,我總是得到_id字段。有沒有辦法取回它? 這是我該怎麼做現在:Mongoose檢索沒有_id字段的數據

Transaction.find({username : user.username}, ['uniqueId', 'timeout', 'confirmation_link', 'item_name'], function(err, txs){ 
     console.log("user : " + user.username + " with txs: " + txs); 
     callback(txs); 
}); 

,並記錄我這包含_id場的結果。

回答

37

_id必須明確排除。例如,

Transaction.find({username : user.username}, { '_id': 0, 'uniqueId' :1, 'timeout': 1, 'confirmation_link': 1, 'item_name': 1}, function(err, txs){ 
    console.log("user : " + user.username + " with txs: " + txs); 
    callback(txs); 
}); 
+2

你可以排除_id並仍然保持ID?我注意到id是一個虛擬的字段。我想要id,但在我的REST API中排除_id。現在,當我排除_id時,id變爲空 – diokey 2015-11-09 02:19:00

60

另一種方法是使用帶有前綴-文本參數,將結果中不包括這個或那個領域:

Entity.find({ ... }, '-_id field1 field2', function(err, entity) { 
    console.log(entity); // { field1: '...', field2: '...' } 
}); 
+1

這似乎是更優雅的語法。 – StephenT 2014-08-24 05:00:58

+1

是比第一個好多了。好一個@VisioN – luxas 2014-12-20 15:51:28

+1

更加優雅! +1 – danilodeveloper 2015-02-02 20:15:01

2

另一種方法:

  • 增廣.toJSON()它刪除了_id__v字段的架構
  • 致電.toJSON()發送給客戶端的所有數據庫對象
  • 額外利益#1:您可以使用item.id === 'something',因爲typeof id === 'string'而不是ObjectId
  • 額外好處#2:當你從客戶端得到gan對象並且你想搜索/更新時,你不必手動刪除_id,因爲沒有,只是被忽略的id

增廣JSON:

mySchema.set('toJSON', { 
    virtuals: true, 
    transform: (doc, ret, options) => { 
     delete ret.__v; 
     ret.id = ret._id.toString(); 
     delete ret._id; 
    }, 
}); 

所以,你可以使用:

let item = (await MyCollection.findOne({/* search */}).exec()).toJSON(); 
if (item.id === 'someString') return item; 

我知道這是醜陋的。但迄今爲止,這是最糟糕的主意。