CleanCrispCode CleanCrispCode - 6 months ago 12
Node.js Question

circular reference error in NodeJS/MongoDB code

I am working on sample application using Node JS , Express , MongoDB , and to access MongoDB from NodeJS am using native mongodb drivers for nodejs.
Below is part of the code which is giving me problem.

module.exports.getLookups = wrap(function * (req , res) {
let users = yield getUsers();
db.close();
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(users));
});

// get users from MEAN mongoDB
function * getUsers(){
return db.collection("users").find({});
}


"res.send(JSON.stringify(users));" line instead of returning json data , it is throwing circular reference error. "users" collection is a simple collection with few records. Please let me know if more info needs to be provided.

Answer

collection.find() returns a Cursor. If you want to read all the results from that cursor, you should call .toArray() on it:

function getUsers(){
 return db.collection("users").find({}).toArray();
}

(getUsers() doesn't have to be a generator function)