Reputation: 4249
I have a database on MongoDB Atlas. Using NodeJS I established a connection and tried to get some data.
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
if(err){
console.log(err)
return res.status(400).json({msg:"Error occured while trying to connect to database", error: err})
}
const collection = client.db("first-test").collection("members")
// perform actions on the collection object
// console.log(collection)
collection.forEach(member => {
console.log(member)
})
client.close();
return res.status(200).json({msg:"success"})
});
When I tried console.log(collection)
I got big object as output (I guess it's what's called a cursor)
Collection {
s: {
pkFactory: [Function: ObjectID] {
index: 4705316,
createPk: [Function: createPk],
createFromTime: [Function: createFromTime],
createFromHexString: [Function: createFromHexString],
isValid: [Function: isValid],
ObjectID: [Circular],
ObjectId: [Circular]
},
db: Db {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter]
},
// And so on ....
When I tried collection.forEach(member => console.log(member))
I got an error TypeError: collection.forEach is not a function
. My question is, how can get my data from the database?
Upvotes: 0
Views: 46
Reputation: 179
I recommend to use mongoose, it's a lot simpler.
But the actual code is
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => throw err);
client.members.find({},(err, res)=>{
console.log(res);
})
Upvotes: 1
Reputation: 70
You are missing the step to "find" all the documents.
ex from w3schools :
dbo.collection("customers").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
Upvotes: 1