Home > Back-end >  "Invalid Message Size" connecting Cosmos DB to Node JS
"Invalid Message Size" connecting Cosmos DB to Node JS

Time:01-24

I am trying to connect Cosmos DB database using Mongoose to my Node JS web app with this code

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

but when running it I get the error MongooseServerSelectionError: Invalid message size: 1347703880, max allowed: 67108864

What im doing wrong??

Thanks in advance

CodePudding user response:

Why are you using mongoose? When you can use @azure/cosmos, it should work fine. Mongoose is an ORM for mongodb.

Install @azure/cosmos

npm install @azure/cosmos --save

Then set up config :

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;

get connection:

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

Create connection:

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

Now, you can query the DB or create items in it. I would suggest you read this article for all the steps if the above steps are not clear.

  •  Tags:  
  • Related