我有两个模型,具有多对少的关系,我正在建模如下:
// Portfolio
const portfoliosSchema = new Schema({
name: { type: String, required: true },
description: { type: String },
user: { type: Schema.Types.ObjectId, ref: 'User', required: true },
positions: [{
stock: { type: Schema.Types.ObjectId, ref: 'Stock', required: true },
cost: number,
amount: number,
}]
});
// Stock
const stocksSchema = new Schema({
exchange: { type: String, required: true },
symbol: { type: String, required: true },
company: { type: String },
description: { type: String }
});
如果不编写自定义服务/以羽毛友好的方式,我将如何:
- 查询投资组合并填充股票的相关记录 收藏
- 简化投资组合架构中嵌套位置的插入/更新(即无需更新整个记录)
这是否受支持/我应该编写自定义服务和/或使关系正常化吗?
编辑 - 解决了第一个使用 before 钩子(Hook)获取额外数据的问题:
function(hook) {
const query = hook.params.query;
hook.params.query = Object.assign({},query,{
$populate: {
path: 'positions.stock',
select: 'exchange symbol'
}
});
}
最佳答案
填充代码示例,根据您的需要进行调整:
Portfolio.find({ some: 'params' })
.populate({ path: 'stock', select: 'name -_id' })
.exec((err, portfolios) => {
res.json({ portfolio: portfolios });
});
更新嵌套数组项:
Position.update({ 'position._id': 'h43q9h94945d948jh098j6h0' }, {
'$set': { 'position.$.whatever': 'your-updated-stuff' }
}, err => {
if (err) return console.log(err));
res.json({ success: true });
});
关于mongodb - 如何使用 feathersjs 处理多对少的 mongodb 关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47614330/