gol*_*cks 6 mongoose express mongodb-query mongoose-populate mongoose-schema
编辑
最小的复制回购
在代码中解释比在英语中更容易.下面的代码可以工作,但感觉就像是一个更简单,更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)
}
Run Code Online (Sandbox Code Playgroud)
我知道如何ref在猫鼬中做一个"常规" ,但是我在这里甚至可能在mongo中吗?
期望的结果:
equipments: [
{
quantity: 1,
name: "Pan",
_id: 'some mongo object here...'
},
{
quantity: 3,
name: "Big Knife",
_id: 'some mongo object here...'
}
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
536 次 |
| 最近记录: |