Menu
CoddyTech

Inserting Documents

Part of the Databases with MongoDB section of Coddy's Node.js journey. Lesson 5 of 29.

A client sends a new book in a POST body, and the server has to store it and say what it stored.

Every document has an _id field, its unique key in the collection. When the object you insert has none, insertOne creates one and also writes it into that same object. The call returns only acknowledged and insertedId, never the document. insertedId is an ObjectId, the kind of id MongoDB generates. Finding by ObjectId explains it.

const movie = { title: 'Alien', year: 1979 };
const result = await movies.insertOne(movie);

console.log(result);    // { acknowledged: true, insertedId: new ObjectId('66f1...') }
console.log(movie._id); // the same id

So after the insert, the object you passed is the stored document, _id included: that is what a client wants back.

The starter seeds three books with insertMany, which takes an array of documents. insertOne takes one document. Both are asynchronous writes.

challenge icon

Challenge

Easy

Clients can now add books. Store the book a client sends, and send it back with its new id.

  1. In server.js, below GET /books, add a POST /books route.
  2. It stores the JSON body as a new document in the books collection.
  3. It responds with status 201 and the book as it was stored, including the _id MongoDB created. For the body in Try it, the response is:
    { "title": "Beloved", "author": "Toni Morrison", "year": 1987, "isbn": "9781400033416", "genre": "literary", "_id": "6720a1f4c2b9e81d3a5f0c14" }
    Your _id will be different. The order of the fields does not matter. Try it: Send POST /books with this body: { "title": "Beloved", "author": "Toni Morrison", "year": 1987, "isbn": "9781400033416", "genre": "literary" }. You get 201 and the book with an _id. Send GET /books: you get four books, with Beloved last. The Data tab shows four documents in books. Press Run again and Beloved is gone. Every Run starts with an empty database, and the starter stores the same three books again.

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.listen(3000, () => {
    console.log('Bookshelf is running on port 3000');
});

All lessons in Databases with MongoDB

Practice on your own: Express playground