Using MONGO DB in shell transform.

72 views
Skip to first unread message

Deepak Bharti

unread,
Jul 1, 2021, 9:02:01 AM7/1/21
to mountebank-discuss
Hi all,
I'm trying to fetch data from mongo db in shell transform.
connection.js
var mongoose = require('mongoose');
var url = "mongodb://localhost:27017/Employee";
var request = JSON.parse(process.env.MB_REQUEST),
     response = JSON.parse(process.env.MB_RESPONSE)
     requestId = request.path.replace('/accounts/', '')
var reqId = parseInt(requestId);

var schema = new mongoose.Schema({ 
    "id": Number,
    "email": String,
    "first_name": String,
    "last_name": String,
    "avatar": String
 },{collection:"Users"});
 let connection = {}
  connection.getUserCollection = () => {
      return mongoose.connect(url, {  useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true }).then((database) => {
          return database.model('Users', schema)
      })
     }
    connection.getUserCollection().then(col=>{
        return col.findOne({id:12}).then(res=>{
            return data(res)         
         })
     }
     )
function data(value){    
   response.body=response.body.replace('${YOU}', value)
}
console.log(JSON.stringify(response))

stubs
[
    {
      "predicates": [{ "matches": { "path": "/accounts/\\d+" } }],
      "responses": [
        {
          "is": { "body": "Hello, ${YOU}!" },
          "behaviors": [
            { "shellTransform": "node scripts/connection/connection.js" }
          ]
        }
      ]
    }
  ]

I'm not getting output as expected



Brandon Byars

unread,
Jul 1, 2021, 11:57:08 AM7/1/21
to Deepak Bharti, mountebank-discuss
Hi there,
It looks to me like your console.log statement is in the wrong place. If I understand the flow of the code correctly, it will execute before your call to mongo, as the callback will not have fired yet. I believe you want to inline your data function and put the console.log statement right below in inside the callback; otherwise the code will return before the database connection has been made:

connection.getUserCollection().then(col=>{
        return col.findOne({id:12}).then(res=>{
            response.body=response.body.replace('${YOU}', res)     
            console.log(JSON.stringify(response))
         })
     }

--
You received this message because you are subscribed to the Google Groups "mountebank-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mountebank-disc...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/mountebank-discuss/0c117c00-bda4-46af-ba2e-0e170b430594n%40googlegroups.com.

Deepak Bharti

unread,
Jul 1, 2021, 12:12:57 PM7/1/21
to Brandon Byars, mountebank-discuss
Hi Brandon,
Thank you for your reply. The changes that you suggested did not worked. So, I have tried it using inject in response. I'm getting the data from DB but when i'm doing config.callback(), it is not working.

Stub:
{
        "predicates":[
            {
                "equals":{
                    "path":"/getData",
                    "method":"GET"
                }
            }
        ],
        "responses":[
            {
                "inject":"function(config){const mongoose = require('mongoose');\n const url = 'mongodb://localhost:27017/Employee';\n var schema = new mongoose.Schema({\n'id': Number,\n'email': String,\n'first_name': String,\n'last_name': String,\n'avatar': String\n},{collection:'Users'});let connection = {};connection.getUserCollection = () => {\nreturn mongoose.connect(url, {  useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true }).then((database) => {\nreturn database.model('Users', schema)\n})\n}\n connection.getUserCollection().then(col=>{\nreturn col.findOne({id:12}).then(res=>{\nconfig.logger.info(res);config.callback({res})\n})\n}\n)}"
            }
        ]
    }
Function for reference:(It is logging the response to the console. How to send it to response?)
"function(config){
const mongoose = require('mongoose');
const url = 'mongodb://localhost:27017/Employee';
var schema = new mongoose.Schema({\n'id': Number,
\n'email': String,
\n'first_name': String,
\n'last_name': String,
\n'avatar': String\n},{collection:'Users'});
let connection = {};
connection.getUserCollection = () => {\n
return mongoose.connect(url, {  useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true })
.then((database) => {\nreturn database.model('Users', schema)\n})\n}\n 
connection.getUserCollection().then(col=>{\nreturn col.findOne({id:12})
.then(res=>{\nconfig.logger.info(res);config.callback({res})\n})\n}\n)}"

Brandon Byars

unread,
Jul 1, 2021, 12:24:42 PM7/1/21
to Deepak Bharti, mountebank-discuss
Hi Deepak,
It's hard to read the function in the raw string format, but I suspect you're dealing with a JavaScript async problem. Abstracting a bit from your situation (and avoiding the need to format your code enough to follow the flow), I think you have something like this:

setup();
async_operation(() => {
  change_response();
  console.log(response);
});
// Nothing here -- so the code returns before the callback has a chance to execute!!!

I would suggest running your script outside of mountebank to troubleshoot (I may be wrong, but I don't think it's a mountebank issue). If you set the environment variables yourself and run your script, does it work? Or is it returning (and ending the process) before the callback has had a chance to fire?
-Brandon

Reply all
Reply to author
Forward
0 new messages