reactjs - 检查对象 Mongoose 中是否存在数组

我的图书模型有这个模式,并且 NoOfLikes 应该将喜欢一本书的用户 id 存储为数组,以及 date 当它被添加到该数组中进行排序时

const bookSchema = new mongoose.Schema({

 noOfLikes : [{
    title: String
    user_id: String,
    dateLiked:{
        type:{type: Date,
               default: Date.now
             }
    }
    }],
})

当我选择一本书时,它应该是这样的

[  
  title: //title of book
  NoOfLikes[
     { 
      user_id: //id of the user who liked
      dateLiked: //date when it is added
     },

     {
      user_id: //id of other user who liked
      dateLiked: //date when it is added
     }
]

现在在我的 api 中,我已经发送了用户喜欢的书的 id 以及用户 id

const { id } = req.params;

并在数据库中选择了这本书

const book = await Book.findById(id);

我也有喜欢的用户 ID,它由我的中间件发送并存储在变量 (_id) 中

现在我想检查用户的_id是否已经存在于已经选择的图书对象的数组中

const index = book.noOfLikes.findIndex({ noOfLikes: {
    $elemMatch: {
      user_id: String(_id)
        }
      }   
    });

但我得到错误不是一个函数//好吧,因为它绝对不是一个函数

我怎样才能正确地做到这一点?

我还想检查 userid(_id) 是否已经存在于该对象数组中,如果不存在,我想将其推送到对象中,否则过滤对象数组并删除数组中的用户 id

//not sure if this will work

if (index === -1) {
      book.noOfLikes.push(_id);
   } 
else {
     book.noOfLikes = book.noOfLikes.filter((id) => id !== String(_id));
    }

回答1

您可以直接使用如下查询

db.collection.find({
  title: "title of book"
},
{
  NoOfLikes: {
    $filter: {
      input: "$NoOfLikes",
      cond: {
        $eq: [
          "$$this.user_id",
          1
        ]
      }
    }
  }
})

工作 https://mongoplayground.net/p/QOG4ePAMgdU

相似文章

随机推荐

最新文章