Importing mongoose returns a 502

answered
#1

Hello!

I’m using Create React App and netlify functions as an bases, regular ES6.

Some of my Package.json:

“mongoose”: “^5.4.16”
“netlify-lambda”: “^1.0.1”
@babel/plugin-transform-object-assign”: “^7.0.0”
“babel-loader”: “8.0.4”

Localy everything works perfect!

But deployed i get following stacktrace:

  1. “”
  2. 1: “SyntaxError: Unexpected token *”
  3. 2: “createScript (vm.js:80:10)”
  4. 3: “Object.runInThisContext (vm.js:139:10)”
  5. 4: “Module._compile (module.js:616:28)”
  6. 5: “Object.Module._extensions…js (module.js:663:10)”
  7. 6: “Module.load (module.js:565:32)”
  8. 7: “tryModuleLoad (module.js:505:12)”
  9. 8: “Function.Module._load (module.js:497:3)”
  10. 9: “Module.require (module.js:596:17)”
  11. 10: “require (internal/module.js:11:18)”

I have removed code and worked out that it is import mongoose that is breaking…
import fetch works great…

Can anyone help me figure out whats wrong?

This is my function:

import mongoose from 'mongoose';

const PROD = process.env.PROD ? true : false;
const MONGODB_USER = process.env.MONGODB_USER;
const MONGODB_PASSWORD = process.env.MONGODB_PASSWORD;
const uri = PROD ? "mongodb+srv://" + MONGODB_USER + ":" + MONGODB_PASSWORD + "@dividend-XYZ.mongodb.net/stocks?retryWrites=true" : "mongodb://localhost:27017/stock";

let conn = null;

exports.handler = async function (event, context) {
  context.callbackWaitsForEmptyEventLoop = false;
  try {
    if (conn == null) {
      conn = await mongoose.createConnection(uri, {
        bufferCommands: false,
        bufferMaxEntries: 0,
        useNewUrlParser: true
      });
      conn.model('Data', new mongoose.Schema({
        isin: String,
        data: mongoose.Schema.Types.Mixed
      }, {
          timestamps: true
        }));
    }
    const Data = conn.model('Data');
    const body = await JSON.parse(event.body);
    let stocks = await Data.find({
      isin: { $in: body }
    });
    return {
      statusCode: 200,
      body: JSON.stringify(stocks.map(stock => stock.data))
    };
  } catch (err) {
    console.error(err);
    return {
      statusCode: 500,
      body: JSON.stringify(err.message)
    }
  }
};
#2

I also had issues with mongoose. Externalizing node_modules did the trick for me: https://github.com/liady/webpack-node-externals

1 Like
#3

Could you explain abit please?

I have intstalled react-app-rewired, and added this to my config-overrides.js

var nodeExternals = require('webpack-node-externals');

module.exports = function override(config, env) {
    //do stuff with the webpack config...
    return {
        ...config,
        target: 'node',
        externals: [nodeExternals()]
    };
}

I have also tried with externals: “mongoose” and did not work.

1 Like
#4

Okey, i have changed from mongoose to mongodb. and it works.

1 Like