如何迭代 objects 的 mongoose 子文档数组

How to iterate on mongoose subdocument array of objects

试图实现依赖于 objects 的子文档数组的条件语句,所以我需要遍历数据库中的 collection 用户,并在 objects 的每个用户子文档数组中检查findIndex 对于 javascript

用户collection

const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
  username: {
    type: String,
    unique: true,
    required: true,
    lowercase: true
  }
  friends: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User"
    }
  ],
  family: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User"
    }
  ],
  acquaintances: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User"
    }
  ],
  following: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User"
    }
  ],
  pendingFriendConfirmationData:[
    {
      storedUserId : {type: String},
      choosenCategories: [{label: {type: String}, value: {type: String}}]
    }
  ]
});

const Users = mongoose.model("Users", userSchema);
module.exports = Users;

现在我可以使用

访问用户 collection
db.Users.find()

我的示例结果

let filter = {"_id": userId}
let projection = {username: 1, friends: 1, family: 1, acquaintances: 1, following: 1, pendingFriendConfirmationData: 1}

db.Users.findOne(filter, projection, (err, user)=>{
      console.log(user)
    })

{
   friends: [],
   family: [],
   acquaintances: [],
   following: [],
   _id: 5ca1a43ac5298f8139b1528c,
   username: 'ahmedyounes',
   pendingFriendConfirmationData: [
     {
       choosenCategories: [Array],
       _id: 5ccb0fcf81a7944faf819883,
       storedUserId: '5cc95d674384e302c9b446e8'
     }
   ]
 }

关注 pendingFriendConfirmationData 以下截图来自 MongoDB Compass

我想像这样迭代

let filter = {"_id": userId}
let projection = {username: 1, friends: 1, family: 1, acquaintances: 1, following: 1, pendingFriendConfirmationData: 1}

db.Users.findOne(filter, projection, (err, user)=>{
      let data = user.pendingFriendConfirmationData
      for(let i in data){
       if(data[i].choosenCategories.findIndex(v => v.label === "friend") !== -1){
        console.log("he is a friend")
      }
      }
    })

如何遍历 pendingFriendConfirmationData 和 choosenCategories 如上

现在如果我console.log(数据)如下

db.Users.findOne(filter, projection, (err, user)=>{
      let data = user.pendingFriendConfirmationData
      console.log(data)
    })

我明白了

我想通了 使用精益更快的 Mongoose 查询

lean 选项告诉 Mongoose 跳过对结果文档的水合。这使得查询速度更快,内存占用更少,但结果文档是普通的 JavaScript 对象(PO​​JO),而不是 Mongoose 文档。在本教程中,您将了解有关使用 lean() 的权衡的更多信息。

在我之前的示例中,解决方案是添加 {lean: true}

db.Users.findOne(filter, projection, {lean: true}, (err, user)=>{
      let data = user.pendingFriendConfirmationData
      console.log(data)
    })

也在这里

db.Users.findOne(filter, projection, {lean: true}, (err, user)=>{
      let data = user.pendingFriendConfirmationData
      for(let i in data){
       if(data[i].choosenCategories.findIndex(v => v.value === "friends") !== -1){
        console.log("he is a friend")
      }
      }
    })

// he is a friend

结论

遍历深度嵌套的子文档对象数组,您需要确保 您正在使用 lean()

处理普通 JavaScript 对象 (POJO)
db.Users.find().lean()