【问题标题】:Update or push object into nested array in found document mongoose在找到的文档 mongoose 中更新或将对象推送到嵌套数组中
【发布时间】:2021-02-10 02:59:07
【问题描述】:

我有这个猫鼬模式:

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"
  }
});

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

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

我该怎么做?首选只是一项操作而不是多项操作。如果我能得到更新 user 那就更好了。

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

谢谢。

【问题讨论】:

    标签: javascript mongodb mongoose


    【解决方案1】:

    我会做这样的事情

    
    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.
        });
    }
    

    【讨论】:

    • 两个pollId都是对象,引用不同,如果两个对象引用不同,即使它们的值相同,它们的比较总是会导致“false”,你必须在末尾添加.toString() pollId 比较。
    • @Ako 不错!我肯定多次遇到过这个错误。
    猜你喜欢
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 2020-11-29
    • 2020-03-27
    • 2019-11-19
    • 1970-01-01
    相关资源
    最近更新 更多