'Mongoose do not return _id and __v
Is it possible to globally tell mongoose to not return the _id and __v fields in Node.js(Typescript)? It is pretty annoying and cluttering to put .select(-_id -__v) on every single query.
Solution 1:[1]
You can make this writing a Mongoose Plugin. A plugin its a function where you can attach hooks to every schema in your app. Here its an example:
module.exports = function deleteId(schema, options) {
schema.post(['find', 'findOne'], function(docs, next) {
if (!Array.isArray(docs)) {
docs = [docs];
}
for (const doc of docs) {
delete doc._id;
}
next()
});
};
If you attach a function to the post find hook, you can delete the _id and then return the documents in your request.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Buenaventura Pino Moslero |
