【问题标题】:Upsert Using an Array Without Creating DuplicatesUpsert 使用数组而不创建重复项
【发布时间】:2017-11-23 10:10:56
【问题描述】:

我无法“更新”到我的阵列。下面的代码在我的answers 数组中创建了我绝对不想要的重复项,现在很明显$push 将不起作用。我已经尝试使用我在 SO 上看到的不同方法有一段时间了,但没有一个对我有用。使用此网络应用程序,用户可以在网站上查看问题并以“是”或“否”response 进行回复,并且他们可以随时更改(更新)他们的response,这意味着一种upsert 在不同时间发生在数据库上。如何解决这个问题?

var QuestionSchema = Schema ({
    title       :String,
    admin       :{type: String, ref: 'User'},
    answers     :[{type:  Schema.Types.Mixed, ref: 'Answer'}]
});

var AnswerSchema = Schema ({
    _question   :{type: ObjectId, ref: 'Question'},
    employee    :{type: String, ref: 'User'},
    response    :String,
    isAdmin     :{type: Boolean, ref: 'User'}
})

var UserSchema = Schema({
    username    : String,
    isAdmin     : {type: Boolean, default: false}
});

module.exports = mongoose.model('Question', QuestionSchema);
module.exports = mongoose.model('Answer', AnswerSchema);
module.exports = mongoose.model('User', UserSchema);


           Question.update(
                {_id: req.body.id},
                {$push: {answers: {_question: req.body.id, 
                                    employee: req.body.employee, 
                                    response: req.body.response, //this variable changes (yes/no/null)
                                     isAdmin: req.body.isAdmin}}},
                {safe: true, upsert: true},
                function(err, model) {

                }
            );

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    在我看来,您似乎有点困惑,这反映在您的架构中。您似乎没有完全理解“嵌入”和“引用”之间的区别,因为您的架构实际上是这两种技术的无效“混搭”。

    可能最好带您了解它们。

    嵌入式模型

    因此,您实际上应该拥有更像这样的东西,而不是您定义的架构:

    var QuestionSchema = Schema ({
        title       :String,
        admin       :{type: String, ref: 'User'},
        answers     :[AnswerSchema]
    });
    
    var AnswerSchema = Schema ({
        employee    :{type: String, ref: 'User'},
        response    :String,
        isAdmin     :{type: Boolean, ref: 'User'}
    })
    
    mongoose.model('Question', questionSchema);
    

    注意Question 是此处唯一的实际模型。 AnswerSchema 是完全“嵌入的”。

    注意“模式”的明确定义,其中Question 中的"answers" 属性被定义为AnswerSchema 的“数组”。这就是你如何嵌入和控制数组内对象中的类型。

    至于更新,有一个明确的逻辑模式,但您根本没有执行它。您需要做的就是“告诉”更新您不想“推送”一个新项目,如果该“唯一”"employee" 在数组中已经存在。

    还有。这是NOT和“upsert”。 Upsert 意味着“创建一个新的”,这与您想要的不同。您想“推送”到“现有”问题的数组。如果您在那里留下“upsert”,那么找不到的东西会创建一个新问题。这当然是错误的。

    Question.update(
      { 
        "_id": req.body.id,
        "answers.employee": { "$ne": req.body.employee },
        }
      },
      { "$push": {
        "answers": { 
          "employee": req.body.employee, 
          "response": req.body.response,
          "isAdmin": req.body.isAdmin
        }
      }},
      function(err, numAffected) {
    
      });
    

    这将检查数组成员中的“唯一”"employee" 是否已经存在,并且只会在它不存在的地方$push

    作为奖励,如果您打算允许用户“更改他们的答案”,那么我们使用 .bulkWrite() 执行此咒语:

    Question.collection.bulkWrite(
      [
        { "updateOne": { 
          "filter": {
            "_id": req.body.id,
            "answers.employee": req.body.employee,
          },
          "update": {
            "$set": {
              "answers.$.response": req.body.response,
            }
          }
        }},
        { "updateOne": { 
          "filter": {
            "_id": req.body.id,
            "answers.employee": { "$ne": req.body.employee },
          },
          "update": {
            "$push": {
              "answers": { 
                "employee": req.body.employee, 
                "response": req.body.response,
                "isAdmin": req.body.isAdmin
              }
            }
          }
        }}
      ],
      function(err, writeResult) {
    
      }
    );
    

    这实际上将两个更新合二为一。第一个尝试更改现有答案并$set 匹配位置的响应,第二个尝试在问题上未找到答案的情况下添加新答案。

    参考模型

    使用“引用”模型,您实际上在自己的集合中拥有Answer 的真实成员。因此,架构是这样定义的:

    var QuestionSchema = Schema ({
        title       :String,
        admin       :{type: String, ref: 'User'},
        answers     :[{ type: Schema.Types.ObjectId, ref: 'Answer' }]
    });
    
    var AnswerSchema = Schema ({
        _question   :{type: ObjectId, ref: 'Question'},
        employee    :{type: String, ref: 'User'},
        response    :String,
        isAdmin     :{type: Boolean, ref: 'User'}
    })
    
    mongoose.model('Answer', answerSchema);
    mongoose.model('Question', questionSchema);
    

    注意另一个参考是User,例如:

        employee    :{type: String, ref: 'User'},
        isAdmin     :{type: Boolean, ref: 'User'}
    

    这些也确实不正确,也应该属于Schema.Type.ObjectId,因为它们“引用”User 的实际_id 字段。但这实际上超出了该问题的范围,因此,如果您在阅读后仍然不明白这一点,那么Ask a New Question 有人可以解释一下。继续回答剩下的问题。

    不过,这是架构的“一般”形状,重要的是 "ref"'Anwser'“模型”,即注册名称。您可以选择在现代猫鼬版本中将"_question" 字段与“虚拟”一起使用,但我现在跳过“高级用法”并通过仍然在Question 模型中的一组“参考”保持简单.

    在这种情况下,由于Answer 模型实际上是在它自己的“集合”中,所以操作实际上变成了“upserts”。当给定的"_question" id 没有"employee" 响应时,我们只想“创建”。

    还使用Promise 链进行演示:

    Answer.update(
      { "_question": req.body.id, "employee": req.body.employee },
      { 
        "$set": {
          "response": req.body.reponse
        },
        "$setOnInsert": {
          "isAdmin": req.body.isAdmin
        }
      },
      { "upsert": true }
    ).then(resp => {
      if ( resp.hasOwnProperty("upserted") ) {
        return Question.update(
          { "_id": req.body.id, "answers": { "$ne": resp.upserted[0]._id  },
          { "$push": { "answers": resp.upserted[0]._id  } }
        ).exec()
      }
      return;
    }).then(resp => {
       // either undefined where it was not an upsert or 
       // the update result from Question where it was
    }).catch(err => { 
       // something
    })
    

    这实际上是一个简单的语句,因为“匹配时”我们想用请求的有效负载更改"response"数据,并且真的只有当“upserting” 或“创建/插入”是当我们实际更改其他数据时,例如 "employee"(始终暗示作为查询表达式的一部分创建)和 "isAdmin",这显然不应该随着我们随后的每个更新请求而改变明确使用$setOnInsert,因此它将这两个字段写入实际的“创建”。

    在“Promise Chain”中,我们实际上是查看对Answer 的更新请求是否真的导致了“upsert”,当它出现时,我们想要追加到Question 的数组中,而它还没有存在。与“嵌入式”示例的方式大致相同,最好先查看数组是否真的有项目,然后再使用“更新”进行修改。或者,您可以在这里$addToSet,让查询与Question 匹配_id。不过对我来说,这是一种浪费。


    总结

    这些是您处理此问题的不同方法。每个都有自己的用例,您可以在其中看到我的一些其他答案的一般摘要:

    不是“必需”阅读,但它可能有助于您深入了解哪种方法最适合您的特定情况。


    工作示例

    复制这些并将它们放在一个目录中并执行npm install 以安装本地依赖项。代码将运行并在进行更改的数据库中创建集合。

    使用mongoose.set(debug,true) 打开日志记录,因此您应该查看控制台输出并查看它的作用,以及生成的集合,其中将记录相关问题的答案,并覆盖而不是“复制”原来的地方也是意图。

    如有必要,请更改连接字符串。但这就是您应该在此列表中更改的所有内容。演示了答案中描述的两种方法。

    package.json

    {
      "name": "colex",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "dependencies": {
        "async": "^2.4.1",
        "mongodb": "^2.2.29",
        "mongoose": "^4.10.7"
      }
    }
    

    index.js

    const async = require('async'),
        mongoose = require('mongoose'),
        Schema = mongoose.Schema,
        ObjectId = require('mongodb').ObjectID
    
    mongoose.Promise = global.Promise;
    mongoose.set('debug',true);
    mongoose.connect('mongodb://localhost/coltest');
    
    const userSchema = new Schema({
      username: String,
      isAdmin: { type: Boolean, default: false }
    });
    
    const answerSchemaA = new Schema({
      employee: { type: Schema.Types.ObjectId, ref: 'User' },
      response: String,
    });
    
    const answerSchemaB = new Schema({
      question: { type: Schema.Types.ObjectId, ref: 'QuestionB' },
      employee: { type: Schema.Types.ObjectId, ref: 'User' },
      response: String,
    });
    
    const questionSchemaA = new Schema({
      title: String,
      admin: { type: Schema.Types.ObjectId, ref: 'User' },
      answers: [answerSchemaA]
    });
    
    const questionSchemaB = new Schema({
      title: String,
      admin: { type: Schema.Types.ObjectId, ref: 'User' },
      answers: [{ type: Schema.Types.ObjectId, ref: 'AnswerB' }]
    });
    
    const User = mongoose.model('User', userSchema);
    
    const AnswerB = mongoose.model('AnswerB', answerSchemaB);
    
    const QuestionA = mongoose.model('QuestionA', questionSchemaA);
    const QuestionB = mongoose.model('QuestionB', questionSchemaB);
    
    
    async.series(
      [
        // Clear data
        (callback) => async.each(mongoose.models,(model,callback) =>
          model.remove({},callback),callback),
    
        // Create some data
        (callback) =>
          async.each([
            {
              "model": "User",
              "object": {
                "_id": "594a322619ddbd437193c759",
                "name": "Admin",
                "isAdmin": true
              }
            },
            {
              "model": "User",
              "object": {
                "_id":  "594a323919ddbd437193c75a",
                "name": "Bill"
              }
            },
            {
              "model": "User",
              "object": {
                "_id":  "594a327b19ddbd437193c75b",
                "name": "Ted"
              }
            },
            {
              "model": "QuestionA",
              "object": {
                "_id": "594a32f719ddbd437193c75c",
                "admin": "594a322619ddbd437193c759",
                "title": "Question A Model"
              }
            },
            {
              "model": "QuestionB",
              "object": {
                "_id": "594a32f719ddbd437193c75c",
                "admin": "594a322619ddbd437193c759",
                "title": "Question B Model"
              }
            }
          ],(data,callback) => mongoose.model(data.model)
            .create(data.object,callback),
          callback
        ),
    
        // Submit Answers for Users - Question A
        (callback) =>
          async.eachSeries(
            [
              {
                "_id": "594a32f719ddbd437193c75c",
                "employee": "594a323919ddbd437193c75a",
                "response": "Bills Answer"
              },
              {
                "_id": "594a32f719ddbd437193c75c",
                "employee": "594a327b19ddbd437193c75b",
                "response": "Teds Answer"
              },
              {
                "_id": "594a32f719ddbd437193c75c",
                "employee": "594a323919ddbd437193c75a",
                "response": "Bills Changed Answer"
              }
            ].map(d => ([
              { "updateOne": {
                "filter": {
                  "_id": ObjectId(d._id),
                  "answers.employee": ObjectId(d.employee)
                },
                "update": {
                  "$set": { "answers.$.response": d.response }
                }
              }},
              { "updateOne": {
                "filter": {
                  "_id": ObjectId(d._id),
                  "answers.employee": { "$ne": ObjectId(d.employee) }
                },
                "update": {
                  "$push": {
                    "answers": {
                      "employee": ObjectId(d.employee),
                      "response": d.response
                    }
                  }
                }
              }}
            ])),
            (data,callback) => QuestionA.collection.bulkWrite(data,callback),
            callback
          ),
    
        // Submit Answers for Users - Question A
        (callback) =>
          async.eachSeries(
            [
              {
                "_id": "594a32f719ddbd437193c75c",
                "employee": "594a323919ddbd437193c75a",
                "response": "Bills Answer"
              },
              {
                "_id": "594a32f719ddbd437193c75c",
                "employee": "594a327b19ddbd437193c75b",
                "response": "Teds Anwser"
              },
              {
                "_id": "594a32f719ddbd437193c75c",
                "employee": "594a327b19ddbd437193c75b",
                "response": "Ted Changed it"
              }
            ],
            (data,callback) => {
              AnswerB.update(
                { "question": data._id, "employee": data.employee },
                { "$set": { "response": data.response } },
                { "upsert": true }
              ).then(resp => {
                console.log(resp);
                if (resp.hasOwnProperty("upserted")) {
                  return QuestionB.update(
                    { "_id": data._id, "employee": { "$ne": data.employee } },
                    { "$push": { "answers": resp.upserted[0]._id } }
                  ).exec()
                }
                return;
              }).then(() => callback(null))
              .catch(err => callback(err))
            },
            callback
          )
      ],
      (err) => {
        if (err) throw err;
        mongoose.disconnect();
      }
    )
    

    【讨论】:

    • 非常感谢或此信息体。我现在更好地理解它了。我修改了我的代码。当我尝试时,我的反应并没有改变。我得到一个 {n: 0, nModified 0, ok 1}。我正在使用bulkWrite
    • @colin_dev256 它对我来说很好用。这两种技术都不是什么新东西,而且我已经实施了很多次。正如我也躲避的那样,您似乎在这里遇到了一些一般概念。不完全确定如何在不列出完整的独立工作示例的情况下使其更清晰。我会立即建议您的“编辑”和“数据”目前不处于可接受的状态。您可能应该在这里从头开始尝试这些概念。
    • 根据我想要达到的目标(你完全明白),我对嵌入式模型的理解已经足够好了。最初我得到一个 TypeError: Invalid value for schema array path answers 直到我将 AnswerSchema 移到 QuestionSchema 上方(因为我用谷歌搜索似乎是问题所在)。错误消失了。这种变化会影响结果吗?
    • @colin_dev256 我无法进行远程调试。要么在您的问题中添加更改的细节,要么耐心等待,而我费力地敲出代码以获得一个完全封闭的示例。如果你发现有用的东西,点个赞就好了:)
    • @colin_dev256 添加了一个完整的示例供您运行,这样您就不会误解任何内容。这至少证明我说的是对的。然后,您可以以此为基础,按照示例编写自己的代码。
    【解决方案2】:

    在尼尔更新他的答案之前,这是我的快速解决方法(我使用了 $pull$push)。和他一样工作,但我会标记他的正确,因为我相信它更有效。

                    Question.update(
                        {_id: req.body.id},
                        {$pull: {answers: { employee: req.body.employee}}},
                        {safe: true, multi:true, upsert: true},
                        function(err, model) {
    
                        }
                    );
    
                    Question.update(
                        {_id: req.body.id},
                        {$push: {answers: {_question: req.body.id, 
                                            employee: req.body.employee, 
                                            response: req.body.response,
                                             isAdmin: req.body.isAdmin}}},
                        {safe: true, upsert: true},
                        function(err, model) {
    
                        }
                    );
    

    【讨论】:

      猜你喜欢
      • 2023-02-07
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多