2018-10-12 15:37:13 -04:00
|
|
|
---
|
|
|
|
title: Chain Search Query Helpers to Narrow Search Results
|
|
|
|
---
|
2019-07-24 00:59:27 -07:00
|
|
|
# Chain Search Query Helpers to Narrow Search Results
|
2018-10-12 15:37:13 -04:00
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
---
|
|
|
|
## Hints
|
|
|
|
|
|
|
|
### Hint 1
|
|
|
|
To create but not execute a find query
|
2018-10-12 15:37:13 -04:00
|
|
|
```javascript
|
2019-07-24 00:59:27 -07:00
|
|
|
Model.find({ name: "Leah" });
|
2018-10-12 15:37:13 -04:00
|
|
|
```
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
### Hint 2
|
|
|
|
To store the find query into a variable for later use:
|
2018-10-12 15:37:13 -04:00
|
|
|
```javascript
|
2019-07-24 00:59:27 -07:00
|
|
|
var findQuery = YourModel.find({ name: "Leah" });
|
2018-10-12 15:37:13 -04:00
|
|
|
```
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
### Hint 3
|
|
|
|
To sort an array:<br>
|
2018-10-12 15:37:13 -04:00
|
|
|
```javascript
|
2019-07-24 00:59:27 -07:00
|
|
|
yourArray.sort({ age: 1 }); // Here: 1 for ascending order and -1 for descending order.
|
2018-10-12 15:37:13 -04:00
|
|
|
```
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
### Hint 4
|
|
|
|
To limit an array's size:
|
2018-10-12 15:37:13 -04:00
|
|
|
```javascript
|
2019-07-24 00:59:27 -07:00
|
|
|
yourArray.limit(5); // return array which has 5 items in it.
|
2018-10-12 15:37:13 -04:00
|
|
|
```
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
### Hint 5
|
|
|
|
To hide certain property from the result:
|
2018-10-12 15:37:13 -04:00
|
|
|
```javascript
|
2019-07-24 00:59:27 -07:00
|
|
|
yourArray.select({ name: 0, age: 1 }); // Here: 0 means false and thus hide name property; 1 means true so age property will show.
|
2018-10-12 15:37:13 -04:00
|
|
|
```
|
2019-07-24 00:59:27 -07:00
|
|
|
### Hint 6
|
|
|
|
To execute this query, you can either:
|
|
|
|
1. Callback:
|
2018-10-12 15:37:13 -04:00
|
|
|
```javascript
|
|
|
|
YourQuery.exec(function(err, docs) {
|
2019-07-24 00:59:27 -07:00
|
|
|
//do something here
|
|
|
|
});
|
2018-10-12 15:37:13 -04:00
|
|
|
```
|
2019-07-24 00:59:27 -07:00
|
|
|
### Hint 7
|
|
|
|
Or
|
|
|
|
|
|
|
|
2. Promise
|
2018-10-12 15:37:13 -04:00
|
|
|
```javascript
|
|
|
|
YourQuery.exec.then(function(err, docs) {
|
2019-07-24 00:59:27 -07:00
|
|
|
//do something here
|
|
|
|
});
|
2018-10-12 15:37:13 -04:00
|
|
|
```
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
### Hint 8
|
|
|
|
Chain it all together:
|
2018-10-12 15:37:13 -04:00
|
|
|
```javascript
|
2019-07-24 00:59:27 -07:00
|
|
|
Person.find({ age: 55 })
|
|
|
|
.sort({ name: -1 })
|
|
|
|
.limit(5)
|
|
|
|
.select({ favoriteFoods: 0 })
|
|
|
|
.exec(function(error, people) {
|
|
|
|
//do something here
|
|
|
|
});
|
2018-10-12 15:37:13 -04:00
|
|
|
```
|