populate mongoose key as part of object
Asked Answered
D

0

6

EDIT
minimal reproduction repo

It's easier to explain in code than English. The following code works, but it feels like there's gotta be an easier, 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 do a "conventional" ref in mongoose, but is what I'm after here even possible in mongo?

desired outcome:

equipments: [
  {
    quantity: 1,
    name: "Pan",
    _id: 'some mongo object here...'
  },
  {
    quantity: 3,
    name: "Big Knife",
    _id: 'some mongo object here...'
  }
]
Devilkin answered 3/4, 2017 at 19:53 Comment(11)
Are you trying to populate ref of sub document from the same collection ? What is .populate('equipments._id') expected to do ? Can you explain a little bit more here ? Why cant you use embedded doc here ?Dayflower
Could you post you expected outcome (in JSON)?Marjana
@DanGreen-Leipciger Added at the end of the question. is that what you meant?Devilkin
Could you post what the raw (from mongo, unprocessed by mongoose) equipments array looks likeMarjana
Right now, it look self-referencingMarjana
Not sure if this is what you are after. You can get the desired outcome by changing your equipments to embedded equipments: [{ _id: Schema.Types.ObjectId, name:String, quantity: { type: Number, required: true, }, }]. Now mongoose should be able to map it when you fetch the recipes. Populate is not applicable here.Dayflower
@Veeram tried it with and without Populating, didn't workDevilkin
@Veeramthe I've added the expected result to the question's body. equipments is a standalone model, with it's own CRUD methods.Devilkin
Can you provide a minimally reproducible set up ?Dayflower
@Veeram Added to the top of the body, thanks :)Devilkin
Can you try with the latest 4.9.6 mongoose version ?Dayflower

© 2022 - 2024 — McMap. All rights reserved.