Finding by ObjectId
Part of the Databases with MongoDB section of Coddy's Node.js journey. Lesson 3 of 18.
To answer one book, the server looks it up by _id, but the id arrives in the URL as text.
An _id that MongoDB creates is an ObjectId: a 12-byte value written as 24 hex characters. JSON shows it as a string, but in the database it is not one, so a filter with the plain text matches nothing. Turn the text into an ObjectId first. ObjectId.isValid says whether a text can be one, because new ObjectId throws on anything else.
import { ObjectId } from 'mongodb';
const text = '66f1c2a9e4b0a1b2c3d4e5f6';
await orders.findOne({ _id: new ObjectId(text) }); // the order, or null
await orders.findOne({ _id: text }); // null: text is not an ObjectId
ObjectId.isValid('42'); // falsefindOne answers the first matching document, or null when none matches.
Challenge
EasyGET /books/:idanswers the book with that_id.- An id that cannot be an ObjectId answers
400. - A valid id with no book answers
404.
Copy an _id from GET /books and send GET /books/<id>. Then send GET /books/42.
Try it yourself
import express from 'express';
import { MongoClient } from 'mongodb';
const client = new MongoClient('mongodb://localhost:27017');
const db = client.db('shelf');
const books = db.collection('books');
await books.insertMany([
{ title: 'Dune', author: 'Frank Herbert', year: 1965, isbn: '9780441013593', genre: 'scifi' },
{ title: 'Kindred', author: 'Octavia E. Butler', year: 1979, isbn: '9780807083697', genre: 'scifi' },
{ title: 'Emma', author: 'Jane Austen', year: 1815, isbn: '9780141439587', genre: 'classic' },
]);
const app = express();
app.use(express.json());
// Every error answers { error: message }.
function sendError(res, status, message) {
res.status(status).json({ error: message });
}
app.get('/', (req, res) => {
res.send('Bookshelf API');
});
app.get('/books', async (req, res) => {
const list = await books.find().toArray();
res.json(list);
});
app.post('/books', async (req, res) => {
const book = req.body;
await books.insertOne(book);
res.status(201).json(book);
});
app.listen(3000, () => {
console.log('Bookshelf is running on port 3000');
});
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Databases with MongoDB
1Documents
Connecting to MongoDBInserting Documents