【问题标题】:How can I check if the user already rated the item in NodeJS & Mongoose Application?如何检查用户是否已经在 NodeJS 和 Mongoose 应用程序中评价了该项目?
【发布时间】:2012-12-14 05:39:23
【问题描述】:

我在 Mongoose 中有以下架构:

UserSchema = new Schema({
    ratings = [{type : Schema.ObjectId, ref : 'Rating'}] })

ItemSchema = new Schema({
    ratings = [{type : Schema.ObjectId, ref : 'Rating'}] })

Rating = new Schema({
    user = [{type : Schema.ObjectId, ref : 'User'}],
    venue = [{type : Schema.ObjectId, ref : 'Venue'}]
})

他们是对的吗?我应该查询用户的评分,项目的评分。另外我想检查用户是否已经评价了一个项目。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您可以使用以下两个选项。

    您可以维护一个单独的集合Rating,这与您在 SQL 中所做的非常相似。

    User: voter (reference to User object),
    Item: item_voted (reference to item object),
    Rating: what so ever user rated
    Time: time_rated,
    other fields as per your requirements...
    

    现在维护UserItem 的索引,以增加查询以检查用户是否已经对某项项目进行评分。

    OR 您可以在User 集合中为该用户评分的项目维护一个数组,并对该数组进行索引。这是您可以为User 提供的数据模型。

    items_rated: [item1, item2, item3]
    other fields of User as per your requirements...
    

    第二种方法有一个限制,如果您的 BSON 记录超过 16MB 限制,它会失败,但在实际使用中,您实际达到该限制的可能性非常小。虽然无话可说。如果你的用户像一些顶级的 stackoverflow 用户一样疯狂,你会碰到 16MB 的墙:P

    您可以检查项目是否已评级的方式(如果您选择第二选择)

    if (db.user.count({item_rated: item_k, _id:'user-id-1'}) == 0) { ... }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-18
      相关资源
      最近更新 更多