0
\$\begingroup\$

I use NodeJS along with the MongoDB NodeJS Driver to store tweets into my local MongoDB server. In the following setup, mongos insertOne method gets invoked quite often by a socket event.

const MongoClient   = require('mongodb').MongoClient;
const TwitterClient = require('node-tweet-stream');

const twitter = new TwitterClient({
    consumer_key: '',
    consumer_secret: '',
    token: '',
    token_secret: ''
});

MongoClient.connect('mongodb://localhost:27017/', { useNewUrlParser: true }).then(client => {
    /**
     * Version 1
     */
    twitter.on('tweet', tweet => {
        client.db('twitter').collection('tweets').insertOne(tweet).then(rs => {
            console.log('tweet received', tweet);
        });
    });

    /**
     * Version 2
     */
    const tweetsCol = client.db('twitter').collection('tweets');

    twitter.on('tweet', tweet => {
        tweetsCol.insertOne(tweet).then(rs => {
            console.log('tweet received', tweet);
        });
    });
});

In version 1 client.db('twitter').collection('tweets').insertOne(tweet) is executed on every tweet event. Whereas in Version 2 the reference of the collection is stored in a variable.

Does the mongodb driver handle such repetitive calls like in version 1 and should I care changing the code structure to version 2 in terms of performance?

\$\endgroup\$
  • 1
    \$\begingroup\$ These code excerpts are so sketchy that I can't even tell whether the code is repetitive or not. \$\endgroup\$ – 200_success Sep 10 at 16:12
  • \$\begingroup\$ The question is: Is calling client.db('news').collection('items') over and over again efficient compared with storing client.db('news') and collection('items') into variables and use them in the actual method which gets invoked say every second. \$\endgroup\$ – Aley Sep 11 at 13:01
  • 1
    \$\begingroup\$ Don't play charades. Show us your code. See How to Ask. \$\endgroup\$ – 200_success Sep 11 at 13:56
  • \$\begingroup\$ @200_success I edited the post. \$\endgroup\$ – Aley Sep 11 at 15:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.