I'm learning Express/Mongo(using mLab) by building a simple little app that I can create a list of clients and a single client detail page.
localhost:3000/clients renders the entire collection of 'clients'
localhost:3000/clients/:id should render the specific client by id
This is a collection: clients entry example from MongoDB (mLab):
{
"_id": {
"$oid": "57ba01d3ab462a0aeec66646"
},
"name": "ClientName",
"address": {
"street": "StreetName",
"city": "Cityname",
"state": "Statename",
"zip": "1234"
},
"createDate": {
"$date": "2016-08-21T19:32:35.525Z"
}
}
I successfully created an href on the /clients page with the id value that links to the specific client:
<a href="/clients/<%= client._id %>"><%= client.name %></a>
Which correctly results in this:
http://localhost:3000/clients/57ba01d3ab462a0aeec66646
Here is my get function for /clients/:id:
app.get('/clients/:id', (req, res) => {
db.collection('clients').findOne(req.params.id, (err, result) => {
if (err) {
handleError(res, err.message, "Failed to get clients.");
} else {
console.log(result);
res.render('client.ejs', {client: result})
}
});
})
Clicking on the link results in the following error:
MongoError: query selector must be an object at Function.MongoError.create (/Users/username/Desktop/node/node_modules/mongodb-core/lib/error.js:31:11) at Collection.find [...]
I've been reading and searching all afternoon and trying a ton of different options like:
- 'You need to create an ObjectID': https://stackoverflow.com/a/10929670
- 'You need to use Mongoose to create the ObjectID': https://stackoverflow.com/a/30652361
Do I really need Mongoose? This seems like a foundational thing to do it Mongo — why isn't it working?