英文:
How to check if item has already existed in array in MongoBD?
问题
如何检查项目是否已存在于数组中?我有一个类似下面的模式模型,我想检查用户ID是否存在于任何字段(可爱、甜美、性感...)中。
const UserSchema = new Schema({
    ...
    vote_user: {
        cute: [Schema.Types.ObjectId],
        sweet: [Schema.Types.ObjectId],
        sexy: [Schema.Types.ObjectId],
    },
    ...
})
英文:
How do I check if item has already existed in array? I have a schema model like below and I want to check if user id existed in any fields (cute, sweet, sexy...).
  const UserSchema = new Schema({
      ...
      vote_user: {
        cute: [Schema.Types.ObjectId], 
        sweet: [Schema.Types.ObjectId], 
        sexy: [Schema.Types.ObjectId],
      },
      ...
  })
答案1
得分: 1
一种选择是使用 $or:
db.collection.find(
  {$or: [
    {cute: userId)},
    {sweet: userId)},
    {sexy: userId)}
  ]}
)
在 playground example 上查看其工作原理。
英文:
One option is using $or:
db.collection.find(
  {$or: [
    {cute: userId)},
    {sweet: userId)},
    {sexy: userId)}
  ]}
)
See how it works on the playground example
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论