2017-12-03 149 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