乐闻世界logo
搜索文章和话题

Mongoose 如何限制查询特定的字段?

5 个月前提问
3 个月前修改
浏览次数57

6个答案

1
2
3
4
5
6

在Mongoose中,限制查询特定字段可以通过以下两种主要方法实现:投影(Projection)和select方法。

投影(Projection)

投影是在查询时指定哪些字段应该返回给用户。在MongoDB和Mongoose中,可以在查询时通过第二个参数定义投影。例如,假设你有一个用户模型User,你只想获取他们的nameemail字段,你可以这样写:

javascript
User.find({}, 'name email', function(err, users) { if (err) { // 处理错误 } else { // 处理查询结果 } });

上面的代码中,'name email'就是一个投影,表示只返回nameemail字段。如果你想排除某些字段,比如不想要password字段,可以在字段前加上-来表示排除:

javascript
User.find({}, '-password', function(err, users) { if (err) { // 处理错误 } else { // 处理查询结果 } });

select方法

另一种方法是使用Mongoose查询的select方法。该方法允许你更链式地构建查询,并且可以更灵活地指定或排除字段。使用select方法时,你也可以使用空格分隔字段名称来指定需要返回的字段,或者使用-来排除字段。例如:

javascript
User.find().select('name email').exec(function(err, users) { if (err) { // 处理错误 } else { // 处理查询结果 } });

或者排除某个字段:

javascript
User.find().select('-password').exec(function(err, users) { if (err) { // 处理错误 } else { // 处理查询结果 } });

在这个例子中,我们使用了链式写法,首先是User.find()来初始化查询,接着是.select('name email')来指定返回的字段,最后是.exec()来执行查询并处理结果。

值得注意的是,使用排除法时,默认情况下_id字段会被包含,除非你显式地排除它。如果你不想返回_id字段,你可以这样写:

javascript
User.find().select('name email -_id').exec(function(err, users) { if (err) { // 处理错误 } else { // 处理查询结果 } });

这些方法也可以与其他查询条件和选项结合使用,以进行更复杂的查询。通过这样的方式,你可以精确控制在Mongoose查询中返回哪些数据,以及如何返回这些数据。

2024年6月29日 12:07 回复

the docs say you can achieve this like so:

Mongoose v4.0

shell
// Retrieving only certain fields Model.find({}, 'first last', function (err, docs) { });

old outdated API

shell
// 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" });

so you can do this without select().

2024年6月29日 12:07 回复

this is another way: queries in mongoose

shell
Transaction.find({username : user.username}) .select('uniqueId confirmation_link item_name timeout username') .exec(function(err, txs) { console.log(txs); });
2024年6月29日 12:07 回复

Now there is a shorter way of doing this (not using .select and not using an array), just passing the fields separate by spaces as the second argument

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

The Docs

2024年6月29日 12:07 回复

Select method is used to select which fields are to be returned in the query result, excluding select means we want all the other fields to be returned, here is simple usage as per the docs.

shell
// include a and b, exclude other fields query.select('a b'); // exclude c and d, include other fields query.select('-c -d');

More information here, https://mongoosejs.com/docs/api.html#query_Query-select

2024年6月29日 12:07 回复

To retrieve certain fields without retrieving the '_id' you can specify to exclude it

shell
Model.find({}, {'Username':1, '_id':0}, function ( err, docs ){}.....
2024年6月29日 12:07 回复

你的答案