1

I have the the following selection query in MongoDb. I want to console log the return of the query.

student.findCourses = (fcallback) => {
    global.db.collection('students').find(({}, { "courses.courseName": true, _id: false }).toArray, (err, result) => {

        if (err) {
            var jError = { "status": "error", "message": "ERROR -> student.js -> 001" }
            console.log(jError)
            return fcallback(true, jError)
        }
        var jOk = { "status": "ok", "message": "student.js -> found -> 000" }
        var jResult = ????
            console.log(jOk)
        return fcallback(false, jOk)

    })
}

Simply I want to see the following in the console.log. And not by manually defining it. I want that it comes directly from the db.

Is there a way to do this?

   {
        "courses": [
            {
                "courseName": "Web-development"
            },
            {
                "courseName": "Databases"
            },
            {
                "courseName": "Databases"
            }
        ]
    }
codeDragon
  • 555
  • 1
  • 8
  • 28

1 Answers1

2

your callback is getting err and result, so in case of success, the result set should be populated to result.

Simply do console.log(JSON.stringify(result); where you print now the jok

One more thing I see that is not ideal on your code- the way you return the result to the callback is not the way it's usually done.
The common practice is to pass error first, and second the result, when in case of success, err should be null (or false).
So following this convention, you can pass in case of error:

return fcallback(err); 

and in case of failure:

return fcallback(null, result);
Nir Levy
  • 12,750
  • 3
  • 21
  • 38
  • does result holds the value of any query you do? – codeDragon Nov 05 '17 at 21:01
  • assuming you are using mongoose, yes. take a look here: http://mongoosejs.com/docs/2.7.x/docs/finding-documents.html, in the simple query example. BTW, I'm not sure why you have `toArray` on your command, might be redundant – Nir Levy Nov 05 '17 at 21:05