gpt4 book ai didi

azure-cosmosdb - 连接到多个 CosmosDB 文档

转载 作者:行者123 更新时间:2023-12-04 10:52:58 28 4
gpt4 key购买 nike

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

谢谢你的帮助!

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

enter image description here

enter image description here

最佳答案

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

  • 确保您已关注 the doc并且您可以在本地成功运行该网站,因为我所有的代码修改都基于此演示。
  • 就我而言,我有一个名为“ToDoList”的数据库,它有两个集合“Items”和“Items2”。

    转至 config.js并为 Items2 添加两个配置:
    config.databaseId2 = "ToDoList";
    config.containerId2 = "Items2";

    enter image description here

  • 转至 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)

    enter image description here

    最后,去 routes/tasklist.js , 修改 constructor方法如下:
       constructor(taskDao,taskDao2) {
    this.taskDao = taskDao;
    this.taskDao2 = taskDao2;
    }

    enter image description here

    完成此步骤后,您的应用程序可以成功连接到您的另一个集合。我在添加任务时将相同的数据写入 items2 集合,转到 addTask方法并添加以下代码:
    await this.taskDao2.addItem(item);

    enter image description here

    好的,让我们启动 Web 应用程序并添加一个任务:
    enter image description here

    检查 cosmos db 中的数据:
    enter image description here
    enter image description here

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

    关于azure-cosmosdb - 连接到多个 CosmosDB 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59379901/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com