williswin
williswin

Reputation: 133

Connecting to multiple CosmosDB documents

I am trying to have multiple documents in Cosmos, one will hold some data from a submit form once it is submitted. I am trying to have a few other documents to hold the data for a drop down select list. How am I able to connect to multiple config.containerId to read some data and then write some data? I am currently only able to read/write to one.

Thanks for any help!

const config = {};

config.host = process.env.HOST || "https://localhost:8081";
config.authKey =
  process.env.AUTH_KEY || "key";
config.databaseId = "ToDoList";
config.containerId = "Items";
config.containerId2 = "List";

if (config.host.includes("https://localhost:")) {
  console.log("Local environment detected");
  console.log("WARNING: Disabled checking of self-signed certs. Do not have this code in production.");
  process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
  console.log(`Go to http://localhost:${process.env.PORT || '3000'} to try the sample.`);
}

module.exports = config;
const CosmosClient = require('@azure/cosmos').CosmosClient
 const config = require('./config')
 const TaskList = require('./routes/tasklist')
 const TaskDao = require('./models/taskDao')



 const express = require('express')
 const path = require('path')
 const logger = require('morgan')
 const cookieParser = require('cookie-parser')
 const bodyParser = require('body-parser')

 const app = express()

 // view engine setup
 app.set('views', path.join(__dirname, 'views'))
 app.set('view engine', 'jade')

 // uncomment after placing your favicon in /public
 //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
 app.use(logger('dev'))
 app.use(bodyParser.json())
 app.use(bodyParser.urlencoded({ extended: false }))
 app.use(cookieParser())
 app.use(express.static(path.join(__dirname, 'public')))

 //Todo App:
 const cosmosClient = new CosmosClient({
   endpoint: config.host,
   key: config.authKey
 })
 const taskDao = new TaskDao(cosmosClient, config.databaseId, config.containerId)
 //const taskDao = new TaskDao(cosmosClient, config.databaseId, config.containerId2)
 const taskList = new TaskList(taskDao)


 taskDao
   .init(err => {
     console.error(err)
   })
   .catch(err => {
     console.error(err)
     console.error(
       'Shutting down because there was an error settinig up the database.'
     )
     process.exit(1)
   })



 app.get('/', (req, res, next) => taskList.showTasks(req, res).catch(next))

 app.post('/addtask', (req, res, next) => taskList.addTask(req, res).catch(next))
 app.post('/completetask', (req, res, next) =>
   taskList.completeTask(req, res).catch(next)
 )
 app.set('view engine', 'jade')


 // catch 404 and forward to error handler
 app.use(function(req, res, next) {
   const err = new Error('Not Found')
   err.status = 404
   next(err)
 })

 // error handler
 app.use(function(err, req, res, next) {
   // set locals, only providing error in development
   res.locals.message = err.message
   res.locals.error = req.app.get('env') === 'development' ? err : {}

   // render the error page
   res.status(err.status || 500)
   res.render('error')
 })



 module.exports = app
form(action="/completetask", method="post")
       label Closure Plan:
       <select name="ClosurePlan" id="ClosurePlanList" type="form" >
       if (typeof tasks === "undefined")
           tr
             td
         else
           each task in tasks
             tr
                <option value="Planned Closure">#{task.name}</option>

Rest of the code is from here:

https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/cosmos-db/sql-api-nodejs-application.md

enter image description here

enter image description here

Upvotes: 2

Views: 126

Answers (1)

Stanley Gong
Stanley Gong

Reputation: 12153

You just need to instantiate another TaskDao to connect to your second container. Pls follow the steps below :

  1. Make sure that you have followed the doc and you can run the website on your local successfully as all my code modification is based on this demo.

  2. In my case, I have a DB named "ToDoList" which has two collections "Items" and "Items2".

    Go to config.js and add two configs for Items2:

    config.databaseId2 = "ToDoList";
    config.containerId2 = "Items2";
    

    enter image description here

Go to app.js , instantiate TaskDao2 :

 const taskDao2 = new TaskDao(cosmosClient, config.databaseId2, config.containerId2)
 taskDao
   .init(err => {
     console.error(err)
   })
   .catch(err => {
     console.error(err)
     console.error(
       'Shutting down because there was an error settinig up the database.'
     )
     process.exit(1)
   })
 taskDao2
 .init(err => {
   console.error(err)
 })
 .catch(err => {
   console.error(err)
   console.error(
     'Shutting down because there was an error settinig up the database.'
   )
   process.exit(1)
 })

 const taskList = new TaskList(taskDao,taskDao2)

enter image description here

Finally, go to routes/tasklist.js, modify constructor method as below :

   constructor(taskDao,taskDao2) {
     this.taskDao = taskDao;
     this.taskDao2 = taskDao2;
   }

enter image description here

With this step is done, your app could connect to your another collection successfully. I write the same data to items2 collection when we adding tasks, go to addTask method and add the code below :

await this.taskDao2.addItem(item);

enter image description here

Ok, lets start the web app and add a task : enter image description here

Have a check the data in cosmos db : enter image description here enter image description here

As you can see, you can write data to another collection now. Hope it helps .

Upvotes: 2

Related Questions