user6680
user6680

Reputation: 139

Azure Function never executes using Mongoose + CosmosDB

I've made an azure function using mongoose. I added the cosmosdb env variables inside the local.settings.json. I did npm init in the folder and installed the following package.

{
  "name": "signup",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "mongoose": "^5.9.1"
  }
}

When I run it in the cloud, it hangs for about a minute, then returns nothing. No status code. No console.log(err). If I run the azure function locally, then it only outputs:

request body I'm using

{"email": "[email protected]", "password": "Password4$", "username" : "bobjones", "over21": true, "role": "Buyer", "phoneNumber": "7383223333", "fullname": null, "address1": null, "address2": null, "city": null, "state": null, "zip": null, "passwordCreated": null}
LETS SIGNUP
Connection to CosmosDB successful

If I deploy it to the cloud to test from there, then when I run it, it'll complete, but nothing outputs. No status code. So it doesn't appear to make it inside the router.post since console.log("inside POST") never outputted. I'm starting to suspect it's a mongoose compatibility issue, but I'm not sure. Does mongoose have limitations with azure functions? I've only seen one article on google talking about mongoose and azure functions so I think it's supported, but not much documentation talking about it. I appreciate any help!


const express = require("express");
const User = require("./models/user");
const mongoose = require("azure-functions-mongooser");
const mongoose1 = require("mongoose");

const router = express.Router();


module.exports = async function (context, req) {


    mongoose1
        .connect(
            "mongodb://" +
            process.env.COSMOSDB_HOST +
            ":" +
            process.env.COSMOSDB_PORT +
            "/" +
            process.env.COSMOSDB_DBNAME +
            "?ssl=true&replicaSet=globaldb",
            {
                auth: {
                    user: process.env.COSMODDB_USER,
                    password: process.env.COSMOSDB_PASSWORD
                }
            }
        )
        .then(() => console.log("Connection to CosmosDB successful"))
        .catch(err => console.error(err));

            console.log("INSIDE POST")

    router.post("/api/signup", (req, res, next) => {
        console.log("SIGNUP BACKEND");

            const user = new User({
                email: req.body.email,
                password: req.body.password,
                username: req.body.username,
                over21: req.body.over21,
                role: req.body.role,
                phoneNumber: req.body.phoneNumber,
                fullName: req.body.fullName,
                address1: req.body.address1,
                address2: req.body.address2,
                city: req.body.city,
                state: req.body.state,
                zip: req.body.zip,
                passwordCreated: Date.now()
            });
            user
                .save()
                .then(result => {
                    console.log("MADE IT");

                    console.log(result);
                    res.status(201).json({
                        message: "User created!",
                        result: result
                    });
                })
                .catch(err => {
                    let error = err.message;
                    console.log(err);
                     if (error.includes("Error, expected `phoneNumber` to be unique.")) {
                        res.status(500).json({
                            error: "Phone number has already been used"
                        });
                    } else if (error.includes("Error, expected `email` to be unique.")) {
                        res.status(500).json({
                            error: "Email has already been used"
                        });
                    }
                });
        });

};



User model

const mongoose = require("mongoose");
//const uniqueValidator = require("mongoose-unique-validator");

const userSchema = mongoose.Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  username: { type: String, required: true, unique: true },
  over21: { type: String, required: true },
  role: { type: String, required: true },
  fullName: { type: String },
  address1: { type: String },
  phoneNumber: { type: String, required: true, unique: true },
  address2: { type: String },
  city: { type: String },
  state: { type: String },
  zip: { type: String },
  passwordCreated: { type: Date },

});


module.exports = mongoose.model("User", userSchema);


Upvotes: 0

Views: 538

Answers (1)

nelak
nelak

Reputation: 380

Actually it is not an issue with mongoose but how you are handling promises in your code. Since your exported function is defined as async all your promises should be awaited using the await keyword otherwise your function will exit before your code completes execution, which is why you don't see any logs in the console. On the other hand as is the code won't return the response you expect because it not returning properly.

You can check the Azure Functions Documentation for more information:

Upvotes: 1

Related Questions