Meteor: Could a race condition happen with Meteor.collections on server side?

后端 未结 3 546
礼貌的吻别
礼貌的吻别 2021-01-05 07:55

in my server/server.js

Meteor.methods({
    saveOnServer: function() {
        var totalCount = Collections.find({
            \"some\": \"condition\"
               


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-05 08:31

    You can make this collection have a unique key on an index field, and then keep it updated as follows:

    1) Whenever you insert into the collection, first do a query to get the maximum index and insert the document with index + 1.

    2) To find out the number of documents just do the query to get the max of the index.

    Insertion is now a pair of queries, a read and a write, so it can fail. (DB ops can always fail, though.) However, it can never leave the database in an inconsistent state - the Mongo index will guarantee that.

    The syntax for building an index in Meteor is this:

    MyCollection._ensureIndex('index', {unique: 1});
    

提交回复
热议问题