如何将对象数组推送到子文档

时间:2019-04-04 11:12:10

标签: node.js mongoose

我有一个成员模型,在家庭成员的子文档中,我正在尝试将对象数组推入子文档中!请帮帮我

会员模型

const memberSchema = new Schema({
  fullName: {
    type: String,
    required: true,
    trim: true
  },
  gender: {
    type: String,
    required: true
  },
  dateOfBirth: {
    type: String,
    required: true
  },
  age: {
    type: Number,
    required: true
  },
  caste: {
    type: String,
    required: true
  },
  education: {
    type: String,
    required: true
  },
  occupation: {
    type: String,
    required: true
  },
  profession: {
    type: String,
    required: true
  },
  address: {
    street: {
      type: String,
      required: true
    },
    city: {
      type: String,
      required: true
    },
    district: {
      type: String,
      required: true
    }
  },
  jobAlerts: {
    type: String,
    enum: ['yes', 'no'],
    required: true
  },
  jobTraining: {
    type: String,
    enum: ['yes', 'no'],
    required: true
  },
  // state: {
  //   type: String,
  //   required: true,
  //   trim: true
  // },
  // taluk:{
  //     type: String,
  //     required:true,
  //     trim:true
  // },  
  userId: {
    type: Schema.Types.ObjectId,
    ref: "User"
  },
  familyMembers: [{ familyMemberSchema }],
  isDeleted: {
    type: Boolean,
    default: false
  },
  verificationStatus: {
    type: Boolean,
    default: false
  },
  paymentStatus: {
    type: Boolean,
    default: false
  },
  referredBy: {
    type: String,
    required: true
  }
});

memberSchema.plugin(timeStamp);
const Member = mongoose.model("Member", memberSchema);

家庭成员架构

const familyMemberSchema = new Schema({
    familyReference: {
        type: Schema.Types.ObjectId,
        required: true,
        ref: 'Member'
    },
    fullName: {
        type: String,
        required: true
    },
    gender: {
        type: String,
        required: true
    },
    dateOfBirth: {
        type: String,
        required: true
    },
    age: {
        type: Number,
        required: true
    },
    education: {
        type: String,
        required: true
    },
    occupation: {
        type: String,
        required: true
    },
    profession: {
        type: String,
        required: true
    },
    userId: {
        type: Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
    isDeleted: {
        type: Boolean,
        default: false
    }
})

module.exports = {
    familyMemberSchema
}

用户控制器

router.post("/register/member", authenticateUser, authorizeVolunteer, async (req, res) => {
  let body;
  let volunteer = req.user.username
  try {
    body = req.body
    // User.findOne(body.mobile).then(registeredUser =>{
    //   if(!registeredUser){

    //   }
    // })
    if (body.familyMembers.length !== 0) {
      let user = new User()
      let member = new Member()
      user.username = body.username
      user.mobile = body.mobile
      user.password = body.password
      let newUser = await user.save()
      member.fullName = body.fullName
      member.gender = body.gender
      member.dateOfBirth = body.dateOfBirth
      member.age = body.age
      member.caste = body.caste
      member.education = body.education
      member.occupation = body.occupation
      member.profession = body.profession
      member.jobAlerts = body.jobAlerts
      member.jobTraining = body.jobTraining
      member.address.street = body.address.street
      member.address.city = body.address.city
      member.address.district = body.address.district
      body.familyMembers.forEach((familyMember) => {
        // return (
        User.findOne({ mobile: familyMember.mobile }).then(registeredUser => {
          if (!registeredUser) {
            let user = new User()
            user.username = familyMember.username
            user.mobile = familyMember.mobile
            user.password = familyMember.password
            let newMember = {}
            newMember.fullName = familyMember.fullName
            newMember.gender = familyMember.gender
            newMember.dateOfBirth = familyMember.dateOfBirth
            newMember.age = familyMember.age
            newMember.education = familyMember.education
            newMember.occupation = familyMember.occupation
            newMember.profession = familyMember.profession
            newMember.userId = user._id
            newMember.familyReference = member._id
            member.familyMembers.push(newMember)
            user.save()
            // .then(newUser => console.log(newUser))
          } else {
            res.send("User already exists")
          }
        })
        // )
      })
      // console.log(body.familyMembers)
      console.log(member.familyMembers)
      member.verificationStatus = true
      member.referredBy = volunteer
      let newMember = await member.save()
      res.send({
        notice: "Successfully Registered",
        newMember
      })

    } else {
      const { username, age, mobile, password, fullName, gender, dateOfBirth, caste, education, occupation, profession, jobAlerts, jobTraining, address: { street, city, district } } = body

      User.findOne({ mobile } || { username }).then(registeredUser => {
        if (!registeredUser) {

          let user = new User({ username, mobile, password })

          let member = new Member({ fullName, age, gender, dateOfBirth, caste, education, occupation, profession, jobAlerts, jobTraining, address: { street, city, district } })

          member.userId = user._id
          user.roles = 'member',
            member.verificationStatus = true
          member.referredBy = volunteer
          Promise.all([member.save(), user.save()]).then(member => {
            res.send({
              notice: 'Successfully registered',
              member,
              status: 201
            })
          })
        } else {
          res.send("User already exists")
        }
      })

    }
  } catch (error) {
    res.send({
      status: 404,
      error: error.message
    })
  }
})

我希望将家庭成员的数据推送到子文档中,每次我遍历re.body并创建对象并将数据推送到db时,

2 个答案:

答案 0 :(得分:0)

body.familyMembers.forEach((familyMember) => {

反复使用带有回调的异步功能太快了,以至于您的循环等待User.findOne首先完成执行。

如果在查询执行时对数组进行控制台操作,则表明该数组到目前为止迭代了太多条目

答案 1 :(得分:0)

    var asyncLoop = require('node-async-loop');
    asyncLoop(array, function (directory, next) {
            // your MongoDB query, your next iteration will not call untill you call next();
            next(); // it will call next iteration of your array
    }, function (err) {
        if (err)
        {
            console.error('Error: ' + err.message);
            return;
        }

        console.log('Finished!'); // it show your looping is done
    });