mongodb - 如何使用 feathersjs 处理多对少的 mongodb 关系?

标签 mongodb mongoose feathersjs feathers-service

我有两个模型,具有多对少的关系,我正在建模如下:

// 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. 简化投资组合架构中嵌套位置的插入/更新(即无需更新整个记录)

这是否受支持/我应该编写自定义服务和/或使关系正常化吗?

编辑 - 解决了第一个使用 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/

相关文章:

MongoDB 没有从 ubuntu 16.04 开始

node.js - 使用 Mongoose 从文档中删除数组元素

javascript - 使用 vuex + Feather 进行异步等待

postgresql - 如何使用 Feather-Sequelize 连接两列进行搜索?

node.js - 将字段添加到从 Mongoose 模式派生的模型中

node.js - mongo ObjectID,ObjectId和Mongoose ObjectId有什么区别

mongodb - 连接到远程 mongo 服务器导致异常连接失败

mongodb - 匹配数组内的多个条件

node.js - Passport 本地身份验证加上 Passport Mongoose 本地不接受电子邮件作为用户名

FeathersJS 查询使用两个 $or but and'ed 在一起