2012-03-03 345 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中以这种方式轻松完成操作。试试这个

相关问题