I am creating a groupedMenu
virtual property that replaces the need for my menu
property.
So once I am done mapping my virtual property, I want to delete the menu key in my Schema.
Example Schema:
new Schema({
menu: [{
category: String
}]
})
Example virtual category being created:
Restaurants.virtual('groupedMenu')
.get(function () {
return _.groupBy(this.menu, menu => menu.category);
});
I've tried deleting the menu in my route, but it does not work. Example:
router.get('/someRoute', function (req, res) {
Schema.findOne({})
.then(menuStuff => {
delete menuStuff.menu // THIS DOES NOT WORK
return res.status(200).json(menuStuff);
})
How can I delete my menu
key after my my virtual property groupedMenu
has been created?
Few issues I see.
Schema.findOne({})
looks quite weird. It should be Model.findOne({})
.
The synonym to virtual
is getter
. This means that when you call object.groupedMenu
the virtual method gets executed. In other words, the groupedMenu
is using the menu
every time you call .groupedMenu
. The virtual properties are not created, they are always executed at runtime.
My suggestion here is to override the Schema.toObject
so that it does not have the .menu
Schema.set("toObject", {
virtuals: true,
transform(doc, ret) {
ret.id = ret._id;
delete ret.menu;
}
});
and use it within your code:
return res.status(200).json(menuStuff.toObject());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.