Inserting Documents
Part of the Databases with MongoDB section of Coddy's Node.js journey. Lesson 2 of 18.
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 answers only acknowledged and insertedId, never the document itself.
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 idSo after the insert, the object you passed is the stored document, _id included: that is what a client wants back.
Challenge
EasyPOST /booksstores the JSON body as a new book.- It answers
201with the stored book, its_idincluded.
Send POST /books with { "title": "Beloved", "author": "Toni Morrison", "year": 1987, "isbn": "9781400033416", "genre": "literary" }. Then send GET /books and look at the Data tab.
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
1Documents
Connecting to MongoDBInserting Documents