"Invalid Message Size" 将 Cosmos DB 连接到 Node JS

"Invalid Message Size" connecting Cosmos DB to Node JS

我正在尝试使用此代码将使用 Mongoose 的 Cosmos DB 数据库连接到我的 Node JS Web 应用程序

const express = require('express')
const path = require('path')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const env = require('dotenv').config();
const User = require('./model/user')

mongoose
        .connect(
            'mongodb://' +
                process.env.COSMOSDB_HOST +
                ':' +
                process.env.COSMOSDB_PORT +
                '/' +
                process.env.COSMOSDB_DBNAME +
                '?ssl=true&replicaSet=globaldb',
            {
                auth: {
                    username: process.env.COSMOSDB_USER,
                    password: process.env.COSMOSDB_PASSWORD,
                },
                useNewUrlParser: true,
                useUnifiedTopology: true,
                retryWrites: false,
            },
        )
        .then(() => console.log('Connection to CosmosDB successful'))
        .catch((err) => console.error('ERRORE: ' + err));

const app = express()
app.use('/',express.static(path.join(__dirname,'public')))
app.use(bodyParser.json())


app.set("view engine", "ejs");
app.get("/", function (req, res) {
    res.render('index')})

app.get("/signup", function (req, res) {
        res.render('register')})
  
        

app.post('/register', async(req,res) =>{
    console.log(req.body)
    res.json({status:'ok'})
})


app.listen(9999,() =>{
    console.log('Server up at 9999')
})

module.exports = app

但是当 运行 时,我得到错误 MongooseServerSelectionError:无效消息大小:1347703880,允许的最大值:67108864

我做错了什么?

你为什么使用猫鼬?当您可以使用 @azure/cosmos 时,它应该可以正常工作。 Mongoose 是 mongodb.

的 ORM

安装@azure/cosmos

npm install @azure/cosmos --save

然后设置配置:

const config = {
  endpoint: "<Your Azure Cosmos account URI>",
  key: "<Your Azure Cosmos account key>",
  databaseId: "Tasks",
  containerId: "Items",
  partitionKey: { kind: "Hash", paths: ["/category"] }
};

module.exports = config;

获取连接:

const config = require("../config");
const CosmosClient = require("@azure/cosmos").CosmosClient;

/*
// This script ensures that the database is setup and populated correctly
*/
async function create(client, databaseId, containerId) {
  const partitionKey = config.partitionKey;

  /**
   * Create the database if it does not exist
   */
  const { database } = await client.databases.createIfNotExists({
    id: databaseId
  });
  console.log(`Created database:\n${database.id}\n`);

  /**
   * Create the container if it does not exist
   */
  const { container } = await client
    .database(databaseId)
    .containers.createIfNotExists(
      { id: containerId, partitionKey },
      { offerThroughput: 400 }
    );

  console.log(`Created container:\n${container.id}\n`);
}

module.exports = { create };

创建连接:

const CosmosClient = require("@azure/cosmos").CosmosClient;
const config = require("./config");
const dbContext = require("./data/databaseContext");

const { endpoint, key, databaseId, containerId } = config;

const client = new CosmosClient({ endpoint, key });

const database = client.database(databaseId);
const container = database.container(containerId);

// Make sure Tasks database is already setup. If not, create it.
await dbContext.create(client, databaseId, containerId);

现在,您可以查询数据库或在其中创建项目。如果以上步骤不清楚,我建议您阅读 this 文章了解所有步骤。