Search code examples
javascriptnode.jsmongooseazure-cosmosdb-mongoapidiscriminator

How do I write data to Cosmos DB using Discriminators, Mongo DB API, and Mongoose?


Problem Summary

I am trying to write a document to my Cosmos DB using the Mongo DB API, and Mongoose for my Object Modeling.

I would like to have all of my documents to be in one collection in order to reduce costs. I would like to achieve this by using Discriminators. This is a Node.js project v14.4.0 and I am using mongodb v3.5.9, and mongoose v5.9.21.

Expected Results

I am able to write a document to a single collection in my Cosmos DB using the above technology stack.

Actual Results

No data is being written to the database. There are no error messages and I am getting undefined logged to my console. More on this in the next section.

What I Have Tried

I have followed the tutorial on how to accomplish my goals located in the Microsoft Docs https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb-mongoose

In addition I have looked at this blog post from Anthony Chu https://anthonychu.ca/post/cosmos-db-mongoose-discriminators/

I have included excerpts of my code below.

Code

./utils/db.js

require('dotenv').config();
const mongoose = require('mongoose');

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

module.exports = mongoose.connection;

./utils/models/models-discriminator.js

const mongoose = require('mongoose');

const baseConfig = {
    discriminatorKey: "_type", //If you've got a lot of different data types, you could also consider setting up a secondary index here.
    collection: "alldata"   //Name of the Common Collection
};

const commonModel = mongoose.model('Common', new mongoose.Schema({}, baseConfig));

const Family_common = commonModel.discriminator('FamilyType', new mongoose.Schema({
    lastName: String,
    parents: [{
        familyName: String,
        firstName: String,
        gender: String
    }],
    children: [{
        familyName: String,
        firstName: String,
       gender: String,
        grade: Number
    }],
    pets:[{
        givenName: String
    }],
    address: {
        country: String,
        state: String,
        city: String
    }
}, baseConfig));

const Vacation_common = commonModel.discriminator('VacationDestinationsType', new mongoose.Schema({
    name: String,
    country: String
}, baseConfig));

module.exports = {
    Family_common,
    Vacation_common,
}

index.js

const { Family_common, Vacation_common } = require('./utils/models/models-discriminator');
const connection = require('./utils/db');
connection.once('open', () => {
  const family_common = new Family_common({
    lastName: "Volum",
    parents: [
      { firstName: "Thomas" },
      { firstName: "Mary Kay" }
    ],
    children: [
      { firstName: "Ryan", gender: "male", grade: 8 },
      { firstName: "Patrick", gender: "male", grade: 7 }
    ],
    pets: [
      { givenName: "Blackie" }
    ],
    address: { country: "USA", state: "WA", city: "Seattle" }
  });

  family_common.save((err, saveFamily) => {
    console.log("Saved: " + JSON.stringify(saveFamily));
  });

  const vacay_common = new Vacation_common({
    name: "Honolulu",
    country: "USA"
  });

  vacay_common.save((err, saveVacay) => {
    console.log("Saved: " + JSON.stringify(saveVacay));
  });
});

Upon running this code this is what is output to my console

Connection to CosmosDB successful

Saved: undefined

Saved: undefined

I would appreciate any assistance you can provide.

Answered by @Darshitpatel Logging the error message in the callback let me figure out why this wasn't working. I have edited the post to show what I had to change to get this to work.


Solution

  • Hi @BradleyGamiMarques,

    I've gone through your code and I think you should log the err parameter in "vacay_common's" save callback.