Return Specific Document Fields using SELECT
Return Specific Document Fields using SELECT Method
▶️ Problem Statement
Suppose User want to see only specific fields of a document, then how to do that?
Like suppose user want to see status of the task http://localhost:5000/api/tasks?select=status
// GET /api/tasks?select=status
{
"status": "completed"
}
▶️ Solution
Specifies which document fields to include or exclude (also known as the query "projection")
You can read more about the SELECT method here (opens in a new tab)
// include a and b, exclude other fields
query.select('a b');
// Equivalent syntaxes:
query.select(['a', 'b']);
query.select({ a: 1, b: 1 });
// exclude c and d, include other fields
query.select('-c -d');
// Use `+` to override schema-level `select: false` without making the
// projection inclusive.
const schema = new Schema({
foo: { type: String, select: false },
bar: String
});
// ...
query.select('+foo'); // Override foo's `select: false` without excluding `bar`
// or you may use object notation, useful when
// you have keys already prefixed with a "-"
query.select({ a: 1, b: 1 });
query.select({ c: 0, d: 0 });
Additional calls to select can override the previous selection:
query.select({ a: 1, b: 1 }).select({ b: 0 }); // selection is now { a: 1 }
query.select({ a: 0, b: 0 }).select({ b: 1 }); // selection is now { a: 0 }
- Like the previous chapter, we saw how use sort method , similarly we can use select method to return specific fields of a document.
const { priority, status, description, sort ,select } = req.query;
let apiData = Task.find(queryObject);
if (select) {
let selectProblem = select.split(",").join(" ");
apiData = apiData.select(selectProblem);
}
console.log(queryObject);
const myData = await apiData;
This is because the select() method in Mongoose expects field names to be separated by a comma so we use split() and join() methods to convert the string to comma separated string and then pass it to the select() method.
- Now we can do
http://localhost:5000/api/tasks?select=status
orhttp://localhost:5000/api/tasks?select=status,description
to get the specific fields of a document.