连接到多个CosmosDB文档 [英] Connecting to multiple CosmosDB documents

查看:67
本文介绍了连接到多个CosmosDB文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Cosmos中拥有多个文档,一旦提交,其中一个将保存来自提交表单的一些数据.我正在尝试其他一些文档来保存下拉选择列表的数据.如何连接到多个config.containerId以读取一些数据然后写入一些数据?我目前只能读写.

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.

感谢您的帮助!

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>

其余代码来自此处:

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

推荐答案

您只需要实例化另一个TaskDao即可连接到第二个容器.请按照以下步骤操作:

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

  1. 确保已遵循

  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.

就我而言,我有一个名为"ToDoList"的数据库,其中有两个集合"Items"和"Items2".

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

转到config.js并为Items2添加两个配置:

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

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

转到app.js,实例化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)

最后,转到routes/tasklist.js,如下修改constructor方法:

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

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

完成此步骤后,您的应用可以成功连接到另一个收藏集.添加任务时,我将相同的数据写入items2集合中,转到addTask方法并添加以下代码:

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);

好吧,让我们启动Web应用程序并添加一个任务:

Ok, lets start the web app and add a task :

检查一下cosmos db中的数据:

Have a check the data in cosmos db :

如您所见,您现在可以将数据写入另一个集合.希望能帮助到你 .

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

这篇关于连接到多个CosmosDB文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆