2017-12-03 144 views
2

我有两个型号,一个多到少的关系,说我建模如下:如何使用feathersjs与许多到很少的mongodb关系?

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

无需编写定制服务/在羽毛友好的方式,怎么会有我:

  1. 查询组合和填充从股票的相关记录 收集
  2. 简化插入/更新投资组合模式中嵌套的位置(即没有更新整个记录)

这是支持/我应该写一个自定义服务和/或规范化的关系?

编辑 - 解决#1前面的勾获得使用额外数据的第一个问题:

function(hook) { 
    const query = hook.params.query; 
    hook.params.query = Object.assign({},query,{ 
    $populate: { 
     path: 'positions.stock', 
     select: 'exchange symbol' 
    } 
    }); 
} 
+0

是的,都支持,寻找一些示例代码为你。 – Alan

回答

0

的填入代码示例,调整你的需求:

Portfolio.find({ some: 'params' }) 
.populate({ path: 'stock', select: 'name -_id' }) 
.exec((err, portfolios) => { 
    res.json({ portfolio: portfolios }); 
}); 

更新嵌套array item:

Position.update({ 'position._id': 'h43q9h94945d948jh098j6h0' }, { 
    '$set': { 'position.$.whatever': 'your-updated-stuff' } 
}, err => { 
    if (err) return console.log(err)); 
    res.json({ success: true }); 
}); 
+0

嗨艾伦,纠正我,如果我错了,但这是如何创建这些查询的猫鼬代码。我如何使用这个与feathersjs - 我必须创建一个自定义服务与这些查询? – cnorris