填充mongoose键作为对象的一部分

时间:2017-04-03 19:53:51

标签: express mongoose mongodb-query mongoose-schema mongoose-populate

修改
minimal reproduction repo

在代码中解释比在英语中更容易。 下面的代码有效,但感觉就像是一个更简单,更MongoDBy / mongoosy的方式...

// 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)
}

我知道如何在猫鼬中做一个“常规”ref,但是我在这里甚至可以在mongo中做什么?

期望的结果:

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

0 个答案:

没有答案