【问题标题】:Where to put the data in mongodb?mongodb的数据放在哪里?
【发布时间】:2020-02-11 21:52:27
【问题描述】:

在 MongoDB 中,我有一个名为 users 的集合。我必须为每个用户存储points。分数可能会随着时间的推移而增加或减少。如果我必须使用 SQL-DB,那么我会将这些点存储在一个名为 UserPoint 的单独表中,其中包含这些列:

UserID, DateTime, CurrentPoint, TotalPoint, Description

我需要获取给定用户的最新TotalPoint 并过于频繁地在UserPoint 表中插入新行。如何在 No-SQL 或 MongoDB 中做同样的事情?我应该创建一个名为 points 的新集合,还是应该在 users 集合中添加一个新的对象数组字段?

{
   points: [
     {
        datetime: XXX,
        currentPoint: YYY,
        totalPoint: ZZZ,
        descriotion: WWW
     },...
   ]
}

【问题讨论】:

    标签: mongodb mongoose nosql


    【解决方案1】:

    我认为在这种情况下,父引用是有意义的。

    而且由于可以根据应用中的点数计算出总点数,因此无需将其保留在其中一个模型中。

    const userSchema = new mongoose.Schema({
      name: String,
      email: String,
      ...
    });
    
    const pointSchema = new mongoose.Schema({
      datetime: date,
      currentPoint: number,
      description: String,
      user: {
        type: mongoose.Schema.ObjectId,
        ref: "User",
        required: [true, "Point must have a user"]
      }
    });
    
    

    所以我们的 User 模型很简单,在点集合中添加一个点非常容易(只是一个常规的插入,没有数组操作)

    【讨论】:

      猜你喜欢
      • 2021-06-02
      • 2013-02-28
      • 2018-03-12
      • 2021-05-09
      • 2022-01-01
      • 1970-01-01
      • 2023-04-10
      • 2010-10-09
      • 1970-01-01
      相关资源
      最近更新 更多