NodeJS and Mongo - Unexpected behaviors when multiple users send requests simultaneously

前端 未结 2 966
自闭症患者
自闭症患者 2021-01-14 03:46

We\'ve been using NodeJS and mongo (via mongoose) to do a very simple save(). We have a model called \"highlights\" which contains an array of ObjectId s that reference \"re

2条回答
  •  醉梦人生
    2021-01-14 04:36

    You're running into a concurrency issue. The way you have your schemas modeled will not ensure atomicity, hence the issues you're experiencing.

    The best option to avoid such problems and to ensure atomicity, would be to nest the Responses model into the Highlights model.

    This way you'd be working only with the Highlights model by pushing a Response element directly into the Responses property of the Highlight model.

    This is the only way to ensure atomicity with MongoDB.

    So you'd have something like this:

       +----------------------+
       |  Highlight model     |
       +----------------------+
       | _id 1                |
       |                      |
       | property 1: 'abc'    |
       | property 2: 'bla'    |
       | property 3: 123      |
       | responses:[          |
       |   +----------------+ |
       |   | Response _id 1 | |
       |   +----------------+,|
       |   | Response _id 2 | |
       |   +----------------+,|
       |   | Response _id 3 | |
       |   +----------------+,|
       |   | Response _id n | |
       |   +----------------+]|
       +----------------------+
    

    Not sure how you do it with Mongoose, but in the mongo shell if you wanted to add a response to the Highlight object with _id ObjectId('1234') you'd do something like this:

        db.highlights.update({_id: ObjectId('1234')},{$push:{Responses: {"Your response object"}}});
    

    $push reference from MongoDB documentation

    I'm pretty sure that you must be able to acomplish this with Mongoose in a simpler way, probably just a matter of browsing it's documentation.

提交回复
热议问题