您如何插入多个文档并使用猫鼬更新它们的重复项?

时间:2018-10-23 07:17:03

标签: javascript node.js mongodb mongoose

我正在尝试使用 insertMany 插入多个文档,但是很少有文档是重复的。对于这些文档,我想对其进行更新。例如:

这些是用户答案文件:

var useranswers = [
  { userid: 1, question: 1, answer: 10},
  { userid: 2, question: 1, answer: 1},
  { userid: 3, question: 1, answer: 11}
]

await UserQuestions.insertMany(useranswers);

每当用户输入问题的答案时,如果要插入该答案,我想对其进行更新。我们如何使用猫鼬来实现此目的?

1 个答案:

答案 0 :(得分:0)

要创建文档或更新文档(如果已存在),可以将update方法与upsert选项一起使用。

在您的情况下:

UserQuestions.update(
    {userid: 1, question: 1}, // Update where userid == 1 and question == 1
    {$set: {userid: 1, question: 1, answer: 10}}, // Set userid = 1, question = 1, answer = 10
    {upsert: true} // Create if it doesnt exists
);

要更新多个文档,您可以想象这样的事情:

var useranswers = [
    { userid: 1, question: 1, answer: 10},
    { userid: 2, question: 1, answer: 1},
    { userid: 3, question: 1, answer: 11}
];

for (var useranswer of useranswers) {
    UserQuestions.update(
        {userid: useranswer.userid, question: useranswer.question},
        {$set: {userid: useranswer.userid, question: useranswer.question, answer: useranswer.answer}},
        {upsert: true}
    );
}

希望有帮助。