Mongoose debug writes to STDERR?

2020-03-27 11:24发布

问题:

First question, ahhhh!

Does anyone know / have info about why mongoose writes its debug log to stderr? Is there anyway to write it to stdout?

回答1:

The debug option accepts a function instead of a boolean:

mongoose.set("debug", function (collection, method, paramA, paramB, paramC) {

    console.log(collection)
    console.log(method)
    console.log(paramA)
    console.log(paramB)
    console.log(paramC)
})

The reason I put paramA, paramB, paramC is because the arguments are dependent upon the method and options being used:

Person.create({firstName: "john"}, callback)
// people
// insert
// {firstName: "john"}
// undefined
// undefined

Person.update({firstName: "john"}, {lastName: "doe"}, {new: true}, callback);
// people
// update
// {firstName: "john"}
// {$set: {lastName: "doe"}}
// {new: true}

Person.find({firstName: "john"}, callback);
// people
// find
// {firstName: "john"}
// undefined
// undefined

Person.find({firstName: "john"}, {limit: 1}, callback);
// people
// find
// {firstName: "john"}
// {limit: 1}
// undefined

The info being logged is the Mongodb input, not the Mongoose input. You can see this in the update() method, paramB comes out as {$set: {lastName: "doe"}}. Behind the scenes, Mongoose converts updates to use $set, which is why that is logged.

From this, you can easily just format it however you want and process.stdout.write()