Cevin Thomas
Cevin Thomas

Reputation: 397

How to make multiple MongoDB trips efficiently

general node mongodb question here.

I have this function:

static addSpaceToCreator = ( userId, spaceId, callback ) => {
        const db = getDb();
        db.collection( process.env.SPACECOLLECTION ).updateOne( { _id: ObjectId( spaceId ) }, { $push: { challengers: ObjectId( userId ) } } );
        db.collection( process.env.USERSCOLLECTION ).updateOne( { _id: ObjectId( userId ) }, { $push: { spaces: ObjectId( spaceId ) } } ).then( r => callback( r ) ).catch( e => callback( e ) );
    };

Question: Is there a better way of making multiple changes like this? I cannot use Bulk because the documents are in different collections. Even if i didn't have a callback, is there a better way of doing 2 .collection trips?

Thank you for your time

Upvotes: 1

Views: 58

Answers (1)

nicholaswmin
nicholaswmin

Reputation: 22989

Use Promise.all to wait for the result of parallel queries, like so:

static addSpaceToCreator = ( userId, spaceId ) => {
    const db = getDb();

    return Promise.all([
      db.collection( process.env.SPACECOLLECTION ).updateOne( { _id: ObjectId( spaceId ) }, { $push: { challengers: ObjectId( userId ) } } ),
      db.collection( process.env.USERSCOLLECTION ).updateOne( { _id: ObjectId( userId ) }, { $push: { spaces: ObjectId( spaceId ) } } ));
    ]);
};

and use it like so:

await addSpaceToCreator(4, 2);

Upvotes: 1

Related Questions