Fill the mongoose key as part of an object

EDIT
minimum repo playback

This is easier to explain in code than in English. The following code works, but it seems you need to be in a simpler, more MongoDBy / mongoosy way ...

// recipeModel.js, relevant part of the schema equipments: [{ _id: { type: Schema.Types.ObjectId, ref: 'equipments', }, quantity: { type: Number, required: true, }, }], // recipeController.js const equipmentsWorkaround = recipe => Object.assign({}, recipe.toObject(), { equipments: recipe.toObject().equipments.map(equip => ({ quantity: equip.quantity, name: equip._id.name, _id: equip._id._id, })), }) const getItem = (req, res, next) => { Recipes.findById(req.params.id) .populate('equipments._id') .then(equipmentsWorkaround) // <--- ugh ... .then(recipe => res.json(recipe)) .catch(next) } 

I know how to make a β€œregular” ref in a mongoose, but what can I do here even after that in a mango?

desired result:

 equipments: [ { quantity: 1, name: "Pan", _id: 'some mongo object here...' }, { quantity: 3, name: "Big Knife", _id: 'some mongo object here...' } ] 
+5
source share

Source: https://habr.com/ru/post/1266274/


All Articles