Eduardo C. K. Ferreira
Eduardo C. K. Ferreira

Reputation: 374

How should I save data in different database collections on Meteor?

I have a Book page submit where I have the Book content, with its unique information, but some data like authors and areas are saved in different collections, linked to the database by the book _id. I am doing like this, but I am almost sure this is not the best way to be done.

Meteor.methods({
bookInsert: function(book, authors, areas) {

// save unique book information
    var bookId = Books.insert(book);

// save each author on a single row on Authors collection
    Object.keys(authors).forEach(function (singleAuthor) {
        var thisAuthor = {
            authorName: authors[singleAuthor],
            bookId: bookId
        }
        var authorId = Authors.insert(thisAuthor);
    });

//save each area on a single row on Areas collection
    Object.keys(areas).forEach(function (singleArea) {
        var thisArea = {
            areaName: areas[singleArea],
            bookId: bookId
        }
        var areaId = Areas.insert(thisArea);
    });

    return {
        _id: bookId
    }
}
})

The issue is that, if some error occurs on Areas Insert for example, book data and authors data have already being saved on database, as it comes before area insert.

Is there a better way to save all these data in different collections, that would prevent this kind of problem? Or this is the correct way to save multiple data on different collections?

Upvotes: 0

Views: 137

Answers (2)

Matt K
Matt K

Reputation: 4948

MongoDB does not have [atomic] transactions, as they would be extremely expensive to implement in the NoSQL structure.

The topic is pretty well covered & if you do a search for transactions in mongo, you'll find some good ideas on how to achieve eventual consistency. For example: http://www.chess-ix.com/blog/transaction-in-mongodb-yes-we-can/

But for my answer, I'd recommend researching schema design in NoSQL. Standard ER modeling is still extremely useful, but then often times it's advantageous to denormalize & nest documents (eg put authors inside the book collection, or books inside authors, depending on your queries). For Meteor devs, here's a good course take next time it comes around: https://university.mongodb.com/courses/M101JS/about

Upvotes: 1

Curtis
Curtis

Reputation: 681

It sounds like you are looking for something like transactions for MongoDB. Unfortunately MongoDB does not explicitly support transactions, however you can still perform a two phase commit to achieve transaction like functionality.

There is a nice tutorial on two phase commits here:

http://docs.mongodb.org/manual/tutorial/perform-two-phase-commits/

Upvotes: 1

Related Questions