首页 > 解决方案 > 更新或将对象推送到找到的文档 mongoose 中的嵌套数组中

问题描述

我有这个猫鼬模式:

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    trim: true
  },
  userId: {
    type: String,
    required: [true, "user ID required."],
    unique: [true, "user ID must be unique"]
  },
  votes: [
    {
      pollId: type: mongoose.Schema.Types.ObjectId,
      candidates: [
        {
          candidateId: mongoose.Schema.Types.ObjectId
        }
      ]
    }
  ],
  role: {
    type: String,
    enum: ["user", "admin"],
    default: "user"
  }
});

我先找到用户,因为我要授权用户。现在我想更新一些部分。只是想清楚一点,我想更新找到的用户文档的某些部分。

我有多个民意调查,用户可以在每个民意调查中投票给多个候选人。因此,如果用户根本没有投票,则投票数组将为空,我们必须推送他/她投票的第一个pollId和第一个 CandidateId。如果pollId存在,我们必须首先通过pollId找到该子文档,然后我们应该在候选数组中添加候选ID。

我怎样才能做到这一点?首选只是一个操作而不是多个操作。如果我能获得更新的用户,那就更好了。

如果不清楚,请告诉我。我会尝试解释更多。

谢谢。

标签: javascriptmongodbmongoose

解决方案


我会做这样的事情


function updateUsersVotes(userId, newVote) {
  User.findById(userId)
    .exec()
    .then((dbUser) => {
      if (!dbUser.votes.length) {     // no votes yet
        dbUser.votes.push(newVote);
      } else {                        // check current votes
        const voteIndex = dbUser.votes.findIndex((vote) => vote.pollId.toString() === newVote.pollId.toString());
        if (voteIndex > 0) {          // if the incoming vote pollId matches an existing pollId
          dbUser.votes[voteIndex].candidates.push(...newVote.candidates);
        } else {
          dbUser.votes.push(newVote); // if the incoming pollId can't be found, then add it.
        }
      }
      dbUser.save({ validateBeforeSave: true }); // update the user.
    })
    .catch((error) => {
      handleError(error);             // you should always handle your errors.
    });
}

推荐阅读