【问题标题】:How to iterate on mongoose subdocument array of objects如何迭代对象的猫鼬子文档数组
【发布时间】:2019-09-21 06:04:02
【问题描述】:

试图实现依赖于子文档对象数组的条件语句,所以我需要遍历数据库中的用户集合,并使用 findIndex 来检查每个用户子文档对象数组的内部,就像 javascript 一样

用户集合

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;

现在我可以使用

访问用户集合
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(data) 如下

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

我明白了

【问题讨论】:

    标签: mongodb mongoose subdocument


    【解决方案1】:

    我想通了Faster Mongoose Queries With Lean

    精益选项告诉 Mongoose 跳过对结果文档进行水合。这使得查询速度更快,内存占用更少,但结果文档是纯 JavaScript 对象 (POJO),而不是 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()
    

    【讨论】:

      猜你喜欢
      • 2020-07-27
      • 2021-10-15
      • 2022-08-18
      • 1970-01-01
      • 2020-07-31
      • 2023-01-31
      • 2021-09-08
      • 1970-01-01
      • 2012-08-26
      相关资源
      最近更新 更多