Dealing with NodeJS asynchronous behavior

前端 未结 2 653
青春惊慌失措
青春惊慌失措 2021-01-22 03:28

Using NodeJS with MongoDB+Mongoose.

First of all, I know the advantages of async non-blocking code. So I do deal with callbacks. But finally I faced the following proble

相关标签:
2条回答
  • 2021-01-22 04:03

    This is a very bad practice, you should never use timers to control the flow of the code.

    The problem here is called atomicity. If you need to do find-save, find-save then you need to pack these operations somehow (transaction). It depends on the software you use. In redis you have the multi and exec commands. In mongodb you have findAndModify(). Another solution is to use an index. When you try to save the same field twice you get an error. Use the attributes, "index: true" and "unique: true" in the schemaType in mongoose:

    var schema = mongoose.Schema ({
        myField: { type: String, index: true, unique: true, required: true },
    });
    

    This is what you need: Mongodb - Isolate sequence of operations - Perform Two Phase Commits. But take into account that mongodb could not be the best choice if you need to do a lot of transactions.

    0 讨论(0)
  • 2021-01-22 04:07

    You don't want to waste RAM, so replace

    lock_function_for_user[user_id] = false
    

    with

    delete lock_function_for_user[user_id]
    

    Apart from that: You could just be optimistic and retry if a conflict happens. Just leave out the locking and make sure that the DB notices when stuff goes wrong (and retry in that case). Of course, which way is better depends on how often such conflicts really happen.

    0 讨论(0)
提交回复
热议问题