简体   繁体   中英

How to create collections dynamically in mongodb with node js

I have huge record to store for each company, one company can contain 200k records. how can we create a dynamic collection for each company with company name to avoid filtration in mongodb.

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://******";
const client = new MongoClient(url, { useNewUrlParser: true });
const dbname='******';
client.connect(err => {
  const db=client.db(dbname);
  const promises = ['Company1','Company2','Company3'].map(name => db.createCollection(name))
  return Promise.all(promises)
    .then(() => {
      client.close()
    })
    .catch(err=>{
        console.log(err)
    })
})

I suggest promise,async,etc.. But if you don't use it, this would create the collections:

client.connect(err => {
  const db=client.db(dbname);
  const companies = ['Company1','Company2','Company3']
  companies.forEach(name=>{
    db.createCollection(name)
  })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM