0

In NodeJS, I have an aggregate MongoDB query with ObjectIDs. I'm simply trying to output the query to a string (e.g. console.log) so that I can copy/paste it into a console and run the query manually.

I can't find any method on the query itself so I'm doing a console.log on the pipeline json.

console.log(JSON.stringify(pipeline));

Which outputs:

[{"$match":{"$and":[{"users.userId":{"$eq":{"_bsontype":"ObjectID","id":{"type":"Buffer","data":[93,151,104,127,56,207,132,25,197,44,232,49]}}}},{"users.userId":{"$eq":{"_bsontype":"ObjectID","id":{"type":"Buffer","data":[93,151,104,127,56,207,132,25,197,44,232,49]}}}}]}}]

This is the result I'm hoping for which runs successfully in the console:

[{"$match":{"$and":[{"users.userId":{"$eq":ObjectId("5d97687f38cf8419c52ce831")}},{"users.userId":{"$eq":ObjectId("5d97687f38cf8419c52ce831")}}]}}]```

2 Answers 2

1

If you are using native client of mongodb for node.js then,

Going by the official docs of mongodb client for node ( http://mongodb.github.io/node-mongodb-native/3.4/reference/connecting/connection-settings/ ),

You can use "loggerLevel" connection option for mongodb, to print the queries.


const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:50000,localhost:50001';
// Database Name
const dbName = 'myproject';

// create a client, passing in additional options
// loggerLevel: debug will print all query on the console
const client = new MongoClient(url, {
  poolSize: 10, tls: true
  loggerLevel: debug 
});

// Use connect method to connect to the server
client.connect(function(err) {
  console.log("Connected correctly to server");
});

else If you are using any ORM for mongoDB such as mongoose (https://mongoosejs.com/docs/connections.html) then,

using mongoose.set('debug', true) will print the queries on the console,



const mongoose = require('mongoose')
const { mongo, env } = require('./vars')

// Exit application on error
mongoose.connection.on('error', (err) => {
  console.error(`MongoDB connection error: ${err}`)
  process.exit(-1)
})

// print mongoose logs in dev env
if (env === 'development') {
  mongoose.set('debug', true)
}

/**
* Connect to mongo db
*/
const connect = async () => {
  await mongoose.connect(mongo.uri, {
    socketTimeoutMS: 60000,
    keepAlive: true,
    useMongoClient: true,
    reconnectTries: 60000,
    poolSize: 10
  })
  return mongoose.connection
}

exports.connect = connect

Sign up to request clarification or add additional context in comments.

Comments

1

The issue is IDs are stored as BSON which clearly had a distinct serializer. If you want to have these serialize in a way compatible with the MongoDB command line, you'd need a custom serializer to convert the ID values.

JSON.stringify has a replacer function you can apply to each key, I can't test this right now but I presume this would work:

JSON.stringify(pipeline, (k, v) => {
  if (k === '$eq') {
    return v.toString()
  }
  return v;
})

This wouldn't give you ObjectId('...') just the value directly (which I think should be fine).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.