Mongoose使用.select()方法
我很困惑与select
方法的使用。 这是我如何使用它,这是错误的:
Transaction.find({username : user.username}).select('uniqueId', 'confirmation_link', 'item_name', 'timeout', 'username', function(err, txs){ callback(txs); });
我想要实现的只是从数据库中的事务中select那个用户名,我想只拿出select
方法中列出的字段。 任何人都可以指出我应该如何使用select
方法? 谢谢。
文档说你可以这样做:
mongoosev4.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()
。
现在有一个更简单的方法(不使用.select
和不使用数组),只是传递由空格分隔的字段作为第二个参数
User.find({}, 'first last', function (err, usr) { //Got the result, saved a few bytes of code });
文档
这是非常有帮助的: 如何保护Mongoose / MongoDB中的密码字段,以便在填充集合时不会在查询中返回?
看起来你有几个select。
1)使用select('-_id')
。 2)使用find({whatever: values}, '-_id', callback...}
我不能validation这个方法,但是如果它和select()
,我不明白为什么它不起作用这里。
这是另一种方式: 在mongoose中查询
Transaction.find({username : user.username}) .select('uniqueId confirmation_link item_name timeout username') .exec(function(err, txs) { console.log(txs); });
要检索某些字段而不检索“_id”,您可以指定将其排除
Model.find({}, {'Username':1, '_id':0}, function ( err, docs ){}.....
要仅检索特定字段,请使用以下内容,
Model.find({/*Your query*/}, {'firstName':1, 'lastname':1, '_id':0}, //Notice, this will omit _id! function ( err, docs ){}.....
这将工作,不会带来任何额外的ID,如_ID。
select和投影操作可以用这种方式在nodejs中轻松完成。 尝试这个
var Selection={ <some key of data model > : <target value for that key field>, <some key of data model > : <target value for that key field> //you can add many parameters here selection operation }; var Projection = { __v : false, _id : false //you can add many parameters here for projection }; <DataModel>.find(Selection,Projection,function (err,data) { if(err){ console.log(err); }else{ console.log(data); } });