【问题标题】:How to get All items associated to a user in mongoose如何在猫鼬中获取与用户关联的所有项目
【发布时间】:2019-10-04 16:26:08
【问题描述】:

我有一个特定的项目集合并执行交易。在我的架构中,我将 userId 与每个项目相关联。我希望能够将用户拥有的所有项目显示为列表。

在这里,我设法将每个项目的所有尺寸加起来,但我无法找出如何为每个用户获取总和的方法

  {
    id: Number,
    x: Number,
    y: Number,
    xSize: String,
    ySize: String,
    imageSource: String,
    user: { type: mongoose.Schema.ObjectId, ref: 'User' }
  },
  { timestamps: true }
);

const UserSchema = new Schema(
  {
    id: Number,
    name: String,
    website: String,

  },
  { timestamps: true }
);

  Item.find({}, function (err, items) {
    var itemMap = {};
    items.forEach(function (item) {
      itemMap[item._id] = item;
    });
    var countedNames = items.reduce(function (allNames, name) {
      if (name.xSize in allNames) {
        allNames[name.xSize]++;
      }
      else {
        allNames[name.xSize] = 1;
      }
      return allNames;
    }, {});

基本上我想得到一个列表,基本上说 {名称:“戴夫”,网站:“www.google.com,项目:[item1,item2]}

其中 item1 和 item2 与项目架构相关

【问题讨论】:

    标签: mongodb express mongoose


    【解决方案1】:

    您应该重写您的UserSchema 以包含对该项目的引用,格式如下:

    const UserSchema = new Schema(
      {
        id: Number,
        name: String,
        website: String,
        items: 
        [{
           item: {type: mongoose.Schema.ObjectId, ref: 'Item'}
        }]
      },
      { timestamps: true }
    );
    

    这将只允许您执行以下查询:

    User.find({}).populate('Item')
    

    这将返回User 文档,以及该文档下关联的所有项目。

    您可以执行以下操作:

    let users = User
        .find({})
        .populate('Item')
        .exec(function (err, users) {
           if (err) { console.log(err); }
           console.log(users)
        }
    

    重写架构将使查询用户的项目更加容易。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-08
      • 2011-11-04
      • 2014-12-27
      • 1970-01-01
      • 2014-05-30
      • 1970-01-01
      • 2021-05-11
      • 1970-01-01
      相关资源
      最近更新 更多