确保猫鼬模式上嵌套引用的唯一索引

时间:2019-08-12 05:43:36

标签: mongodb mongoose indexing

我想要的是用户只能喜欢一次帖子,因此我在user数组中为likes进行了唯一索引,以确保相同,但它不起作用,我可以找不到这里有什么问题。

模式如下:

const mongoose = require('mongoose')

const postSchema = new mongoose.Schema({
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User' // User model
  },
  text: {
    type: String,
    required: [true, 'Post must have some text']
  },
  likes: [
    {
      user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
      }
    }
  ],
  comments: [
    {
      author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
      },
      text: {
        type: String,
        required: [true, 'Comment must have some text']
      },
      addedAt: {
        type: Date,
        default: Date.now
      }
    }
  ],
  createdAt: {
    type: Date,
    default: Date.now
  }
})

postSchema.pre(/^find/, function(next) {
  this.populate({
    path: 'author',
    select: 'name avatar'
  }).populate({
    path: 'comments.author',
    select: 'name avatar'
  })

  next()
})

// Ensure a user can like a post only once
postSchema.index({ 'likes.user': 1 }, { unique: true })

const Post = mongoose.model('Post', postSchema)

module.exports = Post

但是,当我发送发帖请求以通过同一用户两次赞帖子时, 没有显示错误。 这是邮递员的输出Same user in the likes array twice, this shouldn't happen .

我已经尝试了本文中列出的两种方法,但是在这种情况下它们都没有起作用。 Mongoose Index on a field in nested document

如何确保用户只能从架构本身中点赞一次帖子?

1 个答案:

答案 0 :(得分:0)

尝试将这种喜欢的格式保存在数据库中

喜欢:[{{type:mongoose.Schema.Types.ObjectId,ref:'User'}]

做到

likes:[ObjectId(“ 5af03111967c60501d97781f”)]

,当点击类似API的帖子时,请

{$ addToSet:{likedBy:userId}}

在更新查询中,addToSet确保数组中没有重复的ID。