javascript - 更新或将对象推送到找到的文档 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。
我怎样才能做到这一点?首选只是一个操作而不是多个操作。如果我能获得更新的用户,那就更好了。
如果不清楚,请告诉我。我会尝试解释更多。
谢谢。
解决方案
我会做这样的事情
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.
});
}
推荐阅读
- mysql - mysql 语法错误 1064 “NEW”在此服务器版本的此位置无效,需要标识符
- c - 在 C 中的线程之间切换
- java - Azure 函数,azureFunctionsPackage 任务因 java.lang.NullPointerException 而失败
- laravel - Laravel 关系数据返回
- r - 逻辑回归和二元数据
- validation - getRange 从一个文件到另一个文件进行新数据验证
- sql - 检测包含某个值的记录,当它出现在该列中具有不同值的记录之后
- node.js - 我可以存根一个比我正在测试的函数深三层的函数吗
- mysql - 插入新行 - 但前提是它不存在。如果确实存在,则选择要用作外键的行的 id
- kubernetes - Kubernetes master 升级失败后卡在 NotReady