Reputation: 8548
I'm trying to return the saved object as the request response, but I don't want whole object returned by Model.save()
function, it's returning more information than I want, like _id
, __v
.
My request code is like this:
function insertUser(req, res) {
const userName = req.Body.name;
User.save({ name : userName })
.then(r => {
res.send(r);
});
}
It's returning fallowing JSON
to me:
{
_id: 590f529976aa6142d91870b7,
name: 'blablabla'
__v: 4
}
How can I set it to return only { name : 'blablabla' }
?
Upvotes: 0
Views: 100
Reputation: 831
You can write method for this:
Add this method in your user schema: With this method you can control what you return to the client
userSchema.methods.getPublicFields = function() {
return {
name: this.name
};
};
and use it like this
User.save({ name : userName })
.then(r => {
res.send(r.getPublicFields);
});
Upvotes: 1
Reputation: 2810
// transform for sending as json
function omitPrivate(doc, obj) {
delete obj.__v;
delete obj.id;
return obj;
}
// schema options
var options = { toJSON: { transform: omitPrivate } };
// schema
var schema = new Schema({
name: { type: String, required: true },
}, options);
Upvotes: 0