CINXE.COM

Express Tutorial Part 3: Using a Database (with Mongoose) - Learn web development | MDN

<!doctype html><html lang="en-US" prefix="og: https://ogp.me/ns#"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><link rel="icon" href="https://developer.mozilla.org/favicon-48x48.bc390275e955dacb2e65.png"/><link rel="apple-touch-icon" href="https://developer.mozilla.org/apple-touch-icon.528534bba673c38049c2.png"/><meta name="theme-color" content="#ffffff"/><link rel="manifest" href="https://developer.mozilla.org/manifest.f42880861b394dd4dc9b.json"/><link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="MDN Web Docs"/><title>Express Tutorial Part 3: Using a Database (with Mongoose) - Learn web development | MDN</title><link rel="alternate" title="Express-Tutorial Teil 3: Verwendung einer Datenbank (mit Mongoose)" href="https://developer.mozilla.org/de/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose" hrefLang="de"/><link rel="alternate" title="Express チュートリアル Part 3: データベースの使用 (Mongoose を使用)" href="https://developer.mozilla.org/ja/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose" hrefLang="ja"/><link rel="alternate" title="Tutorial Express Parte 3: Usando um banco de dados (com Mongoose)" href="https://developer.mozilla.org/pt-BR/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose" hrefLang="pt"/><link rel="alternate" title="Учебник Express часть 3: Использование базы данных (с помощью Mongoose)" href="https://developer.mozilla.org/ru/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose" hrefLang="ru"/><link rel="alternate" title="Express 教程 3:使用数据库 (Mongoose)" href="https://developer.mozilla.org/zh-CN/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose" hrefLang="zh"/><link rel="alternate" title="Express 教學 3:使用資料庫(Mongoose)" href="https://developer.mozilla.org/zh-TW/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose" hrefLang="zh-Hant"/><link rel="alternate" title="Express Tutorial Part 3: Using a Database (with Mongoose)" href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose" hrefLang="en"/><link rel="preload" as="font" type="font/woff2" href="/static/media/Inter.var.c2fe3cb2b7c746f7966a.woff2" crossorigin=""/><link rel="alternate" type="application/rss+xml" title="MDN Blog RSS Feed" href="https://developer.mozilla.org/en-US/blog/rss.xml" hrefLang="en"/><meta name="description" content="This article briefly introduces databases, and how to use them with Node/Express apps. It then goes on to show how we can use Mongoose to provide database access for the LocalLibrary website. It explains how object schema and models are declared, the main field types, and basic validation. It also briefly shows a few of the main ways in which you can access model data."/><meta property="og:url" content="https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose"/><meta property="og:title" content="Express Tutorial Part 3: Using a Database (with Mongoose) - Learn web development | MDN"/><meta property="og:type" content="website"/><meta property="og:locale" content="en_US"/><meta property="og:description" content="This article briefly introduces databases, and how to use them with Node/Express apps. It then goes on to show how we can use Mongoose to provide database access for the LocalLibrary website. It explains how object schema and models are declared, the main field types, and basic validation. It also briefly shows a few of the main ways in which you can access model data."/><meta property="og:image" content="https://developer.mozilla.org/mdn-social-share.d893525a4fb5fb1f67a2.png"/><meta property="og:image:type" content="image/png"/><meta property="og:image:height" content="1080"/><meta property="og:image:width" content="1920"/><meta property="og:image:alt" content="The MDN Web Docs logo, featuring a blue accent color, displayed on a solid black background."/><meta property="og:site_name" content="MDN Web Docs"/><meta name="twitter:card" content="summary_large_image"/><meta name="twitter:creator" content="MozDevNet"/><link rel="canonical" href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose"/><style media="print">.article-actions-container,.document-toc-container,.language-menu,.main-menu-toggle,.on-github,.page-footer,.place,.sidebar,.top-banner,.top-navigation-main,ul.prev-next{display:none!important}.main-page-content,.main-page-content pre{padding:2px}.main-page-content pre{border-left-width:2px}</style><script src="/static/js/gtag.js" defer=""></script><script defer="" src="/static/js/main.033dd7f3.js"></script><link href="/static/css/main.6ca4d473.css" rel="stylesheet"/></head><body><script>if(document.body.addEventListener("load",(t=>{t.target.classList.contains("interactive")&&t.target.setAttribute("data-readystate","complete")}),{capture:!0}),window&&document.documentElement){const t={light:"#ffffff",dark:"#1b1b1b"};try{const e=window.localStorage.getItem("theme");e&&(document.documentElement.className=e,document.documentElement.style.backgroundColor=t[e]);const o=window.localStorage.getItem("nop");o&&(document.documentElement.dataset.nop=o)}catch(t){console.warn("Unable to read theme from localStorage",t)}}</script><div id="root"><ul id="nav-access" class="a11y-nav"><li><a id="skip-main" href="#content">Skip to main content</a></li><li><a id="skip-search" href="#top-nav-search-input">Skip to search</a></li><li><a id="skip-select-language" href="#languages-switcher-button">Skip to select language</a></li></ul><div class="page-wrapper category-learn document-page"><div class="top-banner loading"><section class="place top container"></section></div><div class="sticky-header-container"><header class="top-navigation "><div class="container "><div class="top-navigation-wrap"><a href="/en-US/" class="logo" aria-label="MDN homepage"><svg id="mdn-docs-logo" xmlns="http://www.w3.org/2000/svg" x="0" y="0" viewBox="0 0 694.9 104.4" style="enable-background:new 0 0 694.9 104.4" xml:space="preserve" role="img"><title>MDN Web Docs</title><path d="M40.3 0 11.7 92.1H0L28.5 0h11.8zm10.4 0v92.1H40.3V0h10.4zM91 0 62.5 92.1H50.8L79.3 0H91zm10.4 0v92.1H91V0h10.4z" class="logo-m"></path><path d="M627.9 95.6h67v8.8h-67v-8.8z" class="logo-_"></path><path d="M367 42h-4l-10.7 30.8h-5.5l-10.8-26h-.4l-10.5 26h-5.2L308.7 42h-3.8v-5.6H323V42h-6.5l6.8 20.4h.4l10.3-26h4.7l11.2 26h.5l5.7-20.3h-6.2v-5.6H367V42zm34.9 20c-.4 3.2-2 5.9-4.7 8.2-2.8 2.3-6.5 3.4-11.3 3.4-5.4 0-9.7-1.6-13.1-4.7-3.3-3.2-5-7.7-5-13.7 0-5.7 1.6-10.3 4.7-14s7.4-5.5 12.9-5.5c5.1 0 9.1 1.6 11.9 4.7s4.3 6.9 4.3 11.3c0 1.5-.2 3-.5 4.7h-25.6c.3 7.7 4 11.6 10.9 11.6 2.9 0 5.1-.7 6.5-2 1.5-1.4 2.5-3 3-4.9l6 .9zM394 51.3c.2-2.4-.4-4.7-1.8-6.9s-3.8-3.3-7-3.3c-3.1 0-5.3 1-6.9 3-1.5 2-2.5 4.4-2.8 7.2H394zm51 2.4c0 5-1.3 9.5-4 13.7s-6.9 6.2-12.7 6.2c-6 0-10.3-2.2-12.7-6.7-.1.4-.2 1.4-.4 2.9s-.3 2.5-.4 2.9h-7.3c.3-1.7.6-3.5.8-5.3.3-1.8.4-3.7.4-5.5V22.3h-6v-5.6H416v27c1.1-2.2 2.7-4.1 4.7-5.7 2-1.6 4.8-2.4 8.4-2.4 4.6 0 8.4 1.6 11.4 4.7 3 3.2 4.5 7.6 4.5 13.4zm-7.7.6c0-4.2-1-7.4-3-9.5-2-2.2-4.4-3.3-7.4-3.3-3.4 0-6 1.2-8 3.7-1.9 2.4-2.9 5-3 7.7V57c0 3 1 5.6 3 7.7s4.5 3.1 7.6 3.1c3.6 0 6.3-1.3 8.1-3.9 1.8-2.7 2.7-5.9 2.7-9.6zm69.2 18.5h-13.2v-7.2c-1.2 2.2-2.8 4.1-4.9 5.6-2.1 1.6-4.8 2.4-8.3 2.4-4.8 0-8.7-1.6-11.6-4.9-2.9-3.2-4.3-7.7-4.3-13.3 0-5 1.3-9.6 4-13.7 2.6-4.1 6.9-6.2 12.8-6.2 5.7 0 9.8 2.2 12.3 6.5V22.3h-8.6v-5.6h15.8v50.6h6v5.5zM493.2 56v-4.4c-.1-3-1.2-5.5-3.2-7.3s-4.4-2.8-7.2-2.8c-3.6 0-6.3 1.3-8.2 3.9-1.9 2.6-2.8 5.8-2.8 9.6 0 4.1 1 7.3 3 9.5s4.5 3.3 7.4 3.3c3.2 0 5.8-1.3 7.8-3.8 2.1-2.6 3.1-5.3 3.2-8zm53.1-1.4c0 5.6-1.8 10.2-5.3 13.7s-8.2 5.3-13.9 5.3-10.1-1.7-13.4-5.1c-3.3-3.4-5-7.9-5-13.5 0-5.3 1.6-9.9 4.7-13.7 3.2-3.8 7.9-5.7 14.2-5.7s11 1.9 14.1 5.7c3 3.7 4.6 8.1 4.6 13.3zm-7.7-.2c0-4-1-7.2-3-9.5s-4.8-3.5-8.2-3.5c-3.6 0-6.4 1.2-8.3 3.7s-2.9 5.6-2.9 9.5c0 3.7.9 6.8 2.8 9.4 1.9 2.6 4.6 3.9 8.3 3.9 3.6 0 6.4-1.3 8.4-3.8 1.9-2.6 2.9-5.8 2.9-9.7zm45 5.8c-.4 3.2-1.9 6.3-4.4 9.1-2.5 2.9-6.4 4.3-11.8 4.3-5.2 0-9.4-1.6-12.6-4.8-3.2-3.2-4.8-7.7-4.8-13.7 0-5.5 1.6-10.1 4.7-13.9 3.2-3.8 7.6-5.7 13.2-5.7 2.3 0 4.6.3 6.7.8 2.2.5 4.2 1.5 6.2 2.9l1.5 9.5-5.9.7-1.3-6.1c-2.1-1.2-4.5-1.8-7.2-1.8-3.5 0-6.1 1.2-7.7 3.7-1.7 2.5-2.5 5.7-2.5 9.6 0 4.1.9 7.3 2.7 9.5 1.8 2.3 4.4 3.4 7.8 3.4 5.2 0 8.2-2.9 9.2-8.8l6.2 1.3zm34.7 1.9c0 3.6-1.5 6.5-4.6 8.5s-7 3-11.7 3c-5.7 0-10.6-1.2-14.6-3.6l1.2-8.8 5.7.6-.2 4.7c1.1.5 2.3.9 3.6 1.1s2.6.3 3.9.3c2.4 0 4.5-.4 6.5-1.3 1.9-.9 2.9-2.2 2.9-4.1 0-1.8-.8-3.1-2.3-3.8s-3.5-1.3-5.8-1.7-4.6-.9-6.9-1.4c-2.3-.6-4.2-1.6-5.7-2.9-1.6-1.4-2.3-3.5-2.3-6.3 0-4.1 1.5-6.9 4.6-8.5s6.4-2.4 9.9-2.4c2.6 0 5 .3 7.2.9 2.2.6 4.3 1.4 6.1 2.4l.8 8.8-5.8.7-.8-5.7c-2.3-1-4.7-1.6-7.2-1.6-2.1 0-3.7.4-5.1 1.1-1.3.8-2 2-2 3.8 0 1.7.8 2.9 2.3 3.6 1.5.7 3.4 1.2 5.7 1.6 2.2.4 4.5.8 6.7 1.4 2.2.6 4.1 1.6 5.7 3 1.4 1.6 2.2 3.7 2.2 6.6zM197.6 73.2h-17.1v-5.5h3.8V51.9c0-3.7-.7-6.3-2.1-7.9-1.4-1.6-3.3-2.3-5.7-2.3-3.2 0-5.6 1.1-7.2 3.4s-2.4 4.6-2.5 6.9v15.6h6v5.5h-17.1v-5.5h3.8V51.9c0-3.8-.7-6.4-2.1-7.9-1.4-1.5-3.3-2.3-5.6-2.3-3.2 0-5.5 1.1-7.2 3.3-1.6 2.2-2.4 4.5-2.5 6.9v15.8h6.9v5.5h-20.2v-5.5h6V42.4h-6.1v-5.6h13.4v6.4c1.2-2.1 2.7-3.8 4.7-5.2 2-1.3 4.4-2 7.3-2s5.3.7 7.5 2.1c2.2 1.4 3.7 3.5 4.5 6.4 1.1-2.5 2.7-4.5 4.9-6.1s4.8-2.4 7.9-2.4c3.5 0 6.5 1.1 8.9 3.3s3.7 5.6 3.7 10.2v18.2h6.1v5.5zm42.5 0h-13.2V66c-1.2 2.2-2.8 4.1-4.9 5.6-2.1 1.6-4.8 2.4-8.3 2.4-4.8 0-8.7-1.6-11.6-4.9-2.9-3.2-4.3-7.7-4.3-13.3 0-5 1.3-9.6 4-13.7 2.6-4.1 6.9-6.2 12.8-6.2s9.8 2.2 12.3 6.5V22.7h-8.6v-5.6h15.8v50.6h6v5.5zm-13.3-16.8V52c-.1-3-1.2-5.5-3.2-7.3s-4.4-2.8-7.2-2.8c-3.6 0-6.3 1.3-8.2 3.9-1.9 2.6-2.8 5.8-2.8 9.6 0 4.1 1 7.3 3 9.5s4.5 3.3 7.4 3.3c3.2 0 5.8-1.3 7.8-3.8 2.1-2.6 3.1-5.3 3.2-8zm61.5 16.8H269v-5.5h6V51.9c0-3.7-.7-6.3-2.2-7.9-1.4-1.6-3.4-2.3-5.7-2.3-3.1 0-5.6 1-7.4 3s-2.8 4.4-2.9 7v15.9h6v5.5h-19.3v-5.5h6V42.4h-6.2v-5.6h13.6V43c2.6-4.6 6.8-6.9 12.7-6.9 3.6 0 6.7 1.1 9.2 3.3s3.7 5.6 3.7 10.2v18.2h6v5.4h-.2z" class="logo-text"></path></svg></a><button title="Open main menu" type="button" class="button action has-icon main-menu-toggle" aria-haspopup="menu" aria-label="Open main menu" aria-expanded="false"><span class="button-wrap"><span class="icon icon-menu "></span><span class="visually-hidden">Open main menu</span></span></button></div><div class="top-navigation-main"><nav class="main-nav" aria-label="Main menu"><ul class="main-menu nojs"><li class="top-level-entry-container "><button type="button" id="references-button" class="top-level-entry menu-toggle" aria-controls="references-menu" aria-expanded="false">References</button><a href="/en-US/docs/Web" class="top-level-entry">References</a><ul id="references-menu" class="submenu references hidden inline-submenu-lg" aria-labelledby="references-button"><li class="apis-link-container mobile-only "><a href="/en-US/docs/Web" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">Overview / Web Technology</div><p class="submenu-item-description">Web technology reference for developers</p></div></a></li><li class="html-link-container "><a href="/en-US/docs/Web/HTML" class="submenu-item "><div class="submenu-icon html"></div><div class="submenu-content-container"><div class="submenu-item-heading">HTML</div><p class="submenu-item-description">Structure of content on the web</p></div></a></li><li class="css-link-container "><a href="/en-US/docs/Web/CSS" class="submenu-item "><div class="submenu-icon css"></div><div class="submenu-content-container"><div class="submenu-item-heading">CSS</div><p class="submenu-item-description">Code used to describe document style</p></div></a></li><li class="javascript-link-container "><a href="/en-US/docs/Web/JavaScript" class="submenu-item "><div class="submenu-icon javascript"></div><div class="submenu-content-container"><div class="submenu-item-heading">JavaScript</div><p class="submenu-item-description">General-purpose scripting language</p></div></a></li><li class="http-link-container "><a href="/en-US/docs/Web/HTTP" class="submenu-item "><div class="submenu-icon http"></div><div class="submenu-content-container"><div class="submenu-item-heading">HTTP</div><p class="submenu-item-description">Protocol for transmitting web resources</p></div></a></li><li class="apis-link-container "><a href="/en-US/docs/Web/API" class="submenu-item "><div class="submenu-icon apis"></div><div class="submenu-content-container"><div class="submenu-item-heading">Web APIs</div><p class="submenu-item-description">Interfaces for building web applications</p></div></a></li><li class="apis-link-container "><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">Web Extensions</div><p class="submenu-item-description">Developing extensions for web browsers</p></div></a></li><li class=" "><a href="/en-US/docs/Web/Accessibility" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">Accessibility</div><p class="submenu-item-description">Build web projects usable for all</p></div></a></li><li class="apis-link-container desktop-only "><a href="/en-US/docs/Web" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">Web Technology</div><p class="submenu-item-description">Web technology reference for developers</p></div></a></li></ul></li><li class="top-level-entry-container active"><button type="button" id="learn-button" class="top-level-entry menu-toggle" aria-controls="learn-menu" aria-expanded="false">Learn</button><a href="/en-US/docs/Learn_web_development" class="top-level-entry">Learn</a><ul id="learn-menu" class="submenu learn hidden inline-submenu-lg" aria-labelledby="learn-button"><li class="apis-link-container mobile-only "><a href="/en-US/docs/Learn_web_development" class="submenu-item "><div class="submenu-icon learn"></div><div class="submenu-content-container"><div class="submenu-item-heading">Overview / MDN Learning Area</div><p class="submenu-item-description">Learn web development</p></div></a></li><li class="apis-link-container desktop-only "><a href="/en-US/docs/Learn_web_development" class="submenu-item "><div class="submenu-icon learn"></div><div class="submenu-content-container"><div class="submenu-item-heading">MDN Learning Area</div><p class="submenu-item-description">Learn web development</p></div></a></li><li class="html-link-container "><a href="/en-US/docs/Learn_web_development/Core/Structuring_content" class="submenu-item "><div class="submenu-icon html"></div><div class="submenu-content-container"><div class="submenu-item-heading">HTML</div><p class="submenu-item-description">Learn to structure web content with HTML</p></div></a></li><li class="css-link-container "><a href="/en-US/docs/Learn_web_development/Core/Styling_basics" class="submenu-item "><div class="submenu-icon css"></div><div class="submenu-content-container"><div class="submenu-item-heading">CSS</div><p class="submenu-item-description">Learn to style content using CSS</p></div></a></li><li class="javascript-link-container "><a href="/en-US/docs/Learn_web_development/Core/Scripting" class="submenu-item "><div class="submenu-icon javascript"></div><div class="submenu-content-container"><div class="submenu-item-heading">JavaScript</div><p class="submenu-item-description">Learn to run scripts in the browser</p></div></a></li><li class=" "><a href="/en-US/docs/Learn_web_development/Core/Accessibility" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">Accessibility</div><p class="submenu-item-description">Learn to make the web accessible to all</p></div></a></li></ul></li><li class="top-level-entry-container "><button type="button" id="mdn-plus-button" class="top-level-entry menu-toggle" aria-controls="mdn-plus-menu" aria-expanded="false">Plus</button><a href="/en-US/plus" class="top-level-entry">Plus</a><ul id="mdn-plus-menu" class="submenu mdn-plus hidden inline-submenu-lg" aria-labelledby="mdn-plus-button"><li class=" "><a href="/en-US/plus" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">Overview</div><p class="submenu-item-description">A customized MDN experience</p></div></a></li><li class=" "><a href="/en-US/plus/ai-help" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">AI Help</div><p class="submenu-item-description">Get real-time assistance and support</p></div></a></li><li class=" "><a href="/en-US/plus/updates" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">Updates</div><p class="submenu-item-description">All browser compatibility updates at a glance</p></div></a></li><li class=" "><a href="/en-US/plus/docs/features/overview" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">Documentation</div><p class="submenu-item-description">Learn how to use MDN Plus</p></div></a></li><li class=" "><a href="/en-US/plus/docs/faq" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">FAQ</div><p class="submenu-item-description">Frequently asked questions about MDN Plus</p></div></a></li></ul></li><li class="top-level-entry-container "><a class="top-level-entry menu-link" href="/en-US/curriculum/">Curriculum <sup class="new">New</sup></a></li><li class="top-level-entry-container "><a class="top-level-entry menu-link" href="/en-US/blog/">Blog</a></li><li class="top-level-entry-container "><button type="button" id="tools-button" class="top-level-entry menu-toggle" aria-controls="tools-menu" aria-expanded="false">Tools</button><ul id="tools-menu" class="submenu tools hidden inline-submenu-lg" aria-labelledby="tools-button"><li class=" "><a href="/en-US/play" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">Playground</div><p class="submenu-item-description">Write, test and share your code</p></div></a></li><li class=" "><a href="/en-US/observatory" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">HTTP Observatory</div><p class="submenu-item-description">Scan a website for free</p></div></a></li><li class=" "><a href="/en-US/plus/ai-help" class="submenu-item "><div class="submenu-icon"></div><div class="submenu-content-container"><div class="submenu-item-heading">AI Help</div><p class="submenu-item-description">Get real-time assistance and support</p></div></a></li></ul></li></ul></nav><div class="header-search"><form action="/en-US/search" class="search-form search-widget" id="top-nav-search-form" role="search"><label id="top-nav-search-label" for="top-nav-search-input" class="visually-hidden">Search MDN</label><input aria-activedescendant="" aria-autocomplete="list" aria-controls="top-nav-search-menu" aria-expanded="false" aria-labelledby="top-nav-search-label" autoComplete="off" id="top-nav-search-input" role="combobox" type="search" class="search-input-field" name="q" placeholder="   " required="" value=""/><button type="button" class="button action has-icon clear-search-button"><span class="button-wrap"><span class="icon icon-cancel "></span><span class="visually-hidden">Clear search input</span></span></button><button type="submit" class="button action has-icon search-button"><span class="button-wrap"><span class="icon icon-search "></span><span class="visually-hidden">Search</span></span></button><div id="top-nav-search-menu" role="listbox" aria-labelledby="top-nav-search-label"></div></form></div><div class="theme-switcher-menu"><button type="button" class="button action has-icon theme-switcher-menu small" aria-haspopup="menu"><span class="button-wrap"><span class="icon icon-theme-os-default "></span>Theme</span></button></div><ul class="auth-container"><li><a href="/users/fxa/login/authenticate/?next=%2Fen-US%2Fdocs%2FLearn_web_development%2FExtensions%2FServer-side%2FExpress_Nodejs%2Fmongoose" class="login-link" rel="nofollow">Log in</a></li><li><a href="/users/fxa/login/authenticate/?next=%2Fen-US%2Fdocs%2FLearn_web_development%2FExtensions%2FServer-side%2FExpress_Nodejs%2Fmongoose" target="_self" rel="nofollow" class="button primary mdn-plus-subscribe-link"><span class="button-wrap">Sign up for free</span></a></li></ul></div></div></header><div class="article-actions-container"><div class="container"><button type="button" class="button action has-icon sidebar-button" aria-label="Expand sidebar" aria-expanded="false" aria-controls="sidebar-quicklinks"><span class="button-wrap"><span class="icon icon-sidebar "></span></span></button><nav class="breadcrumbs-container" aria-label="Breadcrumb"><ol typeof="BreadcrumbList" vocab="https://schema.org/" aria-label="breadcrumbs"><li property="itemListElement" typeof="ListItem"><a href="/en-US/docs/Learn_web_development" class="breadcrumb" property="item" typeof="WebPage"><span property="name">Learn</span></a><meta property="position" content="1"/></li><li property="itemListElement" typeof="ListItem"><a href="/en-US/docs/Learn_web_development/Extensions" class="breadcrumb" property="item" typeof="WebPage"><span property="name">Extension modules</span></a><meta property="position" content="2"/></li><li property="itemListElement" typeof="ListItem"><a href="/en-US/docs/Learn_web_development/Extensions/Server-side" class="breadcrumb" property="item" typeof="WebPage"><span property="name">Server-side website programming</span></a><meta property="position" content="3"/></li><li property="itemListElement" typeof="ListItem"><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs" class="breadcrumb" property="item" typeof="WebPage"><span property="name">Express web framework (Node.js/JavaScript)</span></a><meta property="position" content="4"/></li><li property="itemListElement" typeof="ListItem"><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose" class="breadcrumb-current-page" property="item" typeof="WebPage"><span property="name">Express Tutorial Part 3: Using a Database (with Mongoose)</span></a><meta property="position" content="5"/></li></ol></nav><div class="article-actions"><button type="button" class="button action has-icon article-actions-toggle" aria-label="Article actions"><span class="button-wrap"><span class="icon icon-ellipses "></span><span class="article-actions-dialog-heading">Article Actions</span></span></button><ul class="article-actions-entries"><li class="article-actions-entry"><div class="languages-switcher-menu open-on-focus-within"><button id="languages-switcher-button" type="button" class="button action small has-icon languages-switcher-menu" aria-haspopup="menu"><span class="button-wrap"><span class="icon icon-language "></span>English (US)</span></button><div class="hidden"><ul class="submenu language-menu " aria-labelledby="language-menu-button"><li class=" "><form class="submenu-item locale-redirect-setting"><div class="group"><label class="switch"><input type="checkbox" name="locale-redirect"/><span class="slider"></span><span class="label">Remember language</span></label><a href="https://github.com/orgs/mdn/discussions/739" rel="external noopener noreferrer" target="_blank" title="Enable this setting to automatically switch to this language when it&#x27;s available. (Click to learn more.)"><span class="icon icon-question-mark "></span></a></div></form></li><li class=" "><a data-locale="de" href="/de/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose" class="button submenu-item"><span>Deutsch</span><span title="Diese Übersetzung ist Teil eines Experiments."><span class="icon icon-experimental "></span></span></a></li><li class=" "><a data-locale="ja" href="/ja/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose" class="button submenu-item"><span>日本語</span></a></li><li class=" "><a data-locale="pt-BR" href="/pt-BR/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose" class="button submenu-item"><span>Português (do Brasil)</span></a></li><li class=" "><a data-locale="ru" href="/ru/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose" class="button submenu-item"><span>Русский</span></a></li><li class=" "><a data-locale="zh-CN" href="/zh-CN/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose" class="button submenu-item"><span>中文 (简体)</span></a></li><li class=" "><a data-locale="zh-TW" href="/zh-TW/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose" class="button submenu-item"><span>正體中文 (繁體)</span></a></li></ul></div></div></li></ul></div></div></div></div><div class="main-wrapper"><div class="sidebar-container"><aside id="sidebar-quicklinks" class="sidebar"><button type="button" class="button action backdrop" aria-label="Collapse sidebar"><span class="button-wrap"></span></button><nav aria-label="Related Topics" class="sidebar-inner"><header class="sidebar-actions"><section class="sidebar-filter-container"><div class="sidebar-filter "><label id="sidebar-filter-label" class="sidebar-filter-label" for="sidebar-filter-input"><span class="icon icon-filter"></span><span class="visually-hidden">Filter sidebar</span></label><input id="sidebar-filter-input" autoComplete="off" class="sidebar-filter-input-field false" type="text" placeholder="Filter" value=""/><button type="button" class="button action has-icon clear-sidebar-filter-button"><span class="button-wrap"><span class="icon icon-cancel "></span><span class="visually-hidden">Clear filter input</span></span></button></div></section></header><div class="sidebar-inner-nav"><div class="in-nav-toc"><div class="document-toc-container"><section class="document-toc"><header><h2 class="document-toc-heading">In this article</h2></header><ul class="document-toc-list"><li class="document-toc-item "><a class="document-toc-link" href="#overview">Overview</a></li><li class="document-toc-item "><a class="document-toc-link" href="#designing_the_locallibrary_models">Designing the LocalLibrary models</a></li><li class="document-toc-item "><a class="document-toc-link" href="#mongoose_primer">Mongoose primer</a></li><li class="document-toc-item "><a class="document-toc-link" href="#setting_up_the_mongodb_database">Setting up the MongoDB database</a></li><li class="document-toc-item "><a class="document-toc-link" href="#install_mongoose">Install Mongoose</a></li><li class="document-toc-item "><a class="document-toc-link" href="#connect_to_mongodb">Connect to MongoDB</a></li><li class="document-toc-item "><a class="document-toc-link" href="#defining_the_locallibrary_schema">Defining the LocalLibrary Schema</a></li><li class="document-toc-item "><a class="document-toc-link" href="#testing_—_create_some_items">Testing — create some items</a></li><li class="document-toc-item "><a class="document-toc-link" href="#summary">Summary</a></li><li class="document-toc-item "><a class="document-toc-link" href="#see_also">See also</a></li></ul></section></div></div><div class="sidebar-body"><ol><li class="section"><a href="/en-US/docs/Learn_web_development/Getting_started">Getting started modules</a></li><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Getting_started/Environment_setup">Environment setup</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Getting_started/Environment_setup/Installing_software">Installing basic software</a></li><li><a href="/en-US/docs/Learn_web_development/Getting_started/Environment_setup/Browsing_the_web">Browsing the web</a></li><li><a href="/en-US/docs/Learn_web_development/Getting_started/Environment_setup/Code_editors">Code editors</a></li><li><a href="/en-US/docs/Learn_web_development/Getting_started/Environment_setup/Dealing_with_files">Dealing with files</a></li><li><a href="/en-US/docs/Learn_web_development/Getting_started/Environment_setup/Command_line">Command line crash course</a></li></ol></details></li><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Getting_started/Your_first_website">Your first website</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Getting_started/Your_first_website/What_will_your_website_look_like">What will your website look like?</a></li><li><a href="/en-US/docs/Learn_web_development/Getting_started/Your_first_website/Creating_the_content">HTML: Creating the content</a></li><li><a href="/en-US/docs/Learn_web_development/Getting_started/Your_first_website/Styling_the_content">CSS: Styling the content</a></li><li><a href="/en-US/docs/Learn_web_development/Getting_started/Your_first_website/Adding_interactivity">JavaScript: Adding interactivity</a></li><li><a href="/en-US/docs/Learn_web_development/Getting_started/Your_first_website/Publishing_your_website">Publishing your website</a></li></ol></details></li><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Getting_started/Web_standards">Web standards</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Getting_started/Web_standards/How_the_web_works">How the web works</a></li><li><a href="/en-US/docs/Learn_web_development/Getting_started/Web_standards/The_web_standards_model">The web standards model</a></li><li><a href="/en-US/docs/Learn_web_development/Getting_started/Web_standards/How_browsers_load_websites">How browsers load websites</a></li></ol></details></li><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Getting_started/Soft_skills">Soft skills</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Getting_started/Soft_skills/Research_and_learning">Research and learning</a></li><li><a href="/en-US/docs/Learn_web_development/Getting_started/Soft_skills/Collaboration_and_teamwork">Collaboration and teamwork</a></li><li><a href="/en-US/docs/Learn_web_development/Getting_started/Soft_skills/Workflows_and_processes">Workflows and processes</a></li><li><a href="/en-US/docs/Learn_web_development/Getting_started/Soft_skills/Job_interviews">Succeeding in job interviews</a></li></ol></details></li><li class="section"><a href="/en-US/docs/Learn_web_development/Core">Core modules</a></li><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Core/Structuring_content">Structuring content with HTML</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Core/Structuring_content/Basic_HTML_syntax">Basic HTML syntax</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Structuring_content/Webpage_metadata">What's in the head? Webpage metadata</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Structuring_content/Headings_and_paragraphs">Headings and paragraphs in HTML</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Structuring_content/Emphasis_and_importance">Emphasis and importance</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Structuring_content/Lists">Lists</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Structuring_content/Structuring_documents">Structuring documents</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Structuring_content/Advanced_text_features">Advanced text features</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Structuring_content/Creating_links">Creating links</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Structuring_content/Marking_up_a_letter">Challenge: Marking up a letter</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Structuring_content/Structuring_a_page_of_content">Challenge: Structuring a page of content</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Structuring_content/HTML_images">HTML images</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Structuring_content/HTML_video_and_audio">HTML video and audio</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Structuring_content/Mozilla_splash_page">Challenge: Mozilla splash page</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Structuring_content/HTML_table_basics">HTML table basics</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Structuring_content/Table_accessibility">HTML table accessibility</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Structuring_content/Planet_data_table">Challenge: Structuring a planet data table</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Structuring_content/HTML_forms">Forms and buttons in HTML</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Structuring_content/Debugging_HTML">Debugging HTML</a></li></ol></details></li><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Core/Styling_basics">CSS styling basics</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Core/Styling_basics/What_is_CSS">What is CSS?</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Styling_basics/Getting_started">Getting started with CSS</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Styling_basics/Styling_a_bio_page">Challenge: Styling a biography page</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Styling_basics/Basic_selectors">Basic CSS selectors</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Styling_basics/Attribute_selectors">Attribute selectors</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Styling_basics/Pseudo_classes_and_elements">Pseudo-classes and pseudo-elements</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Styling_basics/Combinators">Combinators</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Styling_basics/Box_model">The box model</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Styling_basics/Handling_conflicts">Handling conflicts</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Styling_basics/Values_and_units">CSS values and units</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Styling_basics/Sizing">Sizing items in CSS</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Styling_basics/Backgrounds_and_borders">Backgrounds and borders</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Styling_basics/Overflow">Overflowing content</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Styling_basics/Images_media_forms">Images, media, and form elements</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Styling_basics/Tables">Styling tables</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Styling_basics/Debugging_CSS">Debugging CSS</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Styling_basics/Fundamental_CSS_comprehension">Challenge: Fundamental CSS comprehension</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Styling_basics/Fancy_letterheaded_paper">Challenge: Creating fancy letterheaded paper</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Styling_basics/Cool-looking_box">Challenge: A cool-looking box</a></li></ol></details></li><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Core/Text_styling">CSS text styling</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Core/Text_styling/Fundamentals">Fundamental text and font styling</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Text_styling/Styling_lists">Styling lists</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Text_styling/Styling_links">Styling links</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Text_styling/Web_fonts">Web fonts</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Text_styling/Typesetting_a_homepage">Challenge: Typesetting a community school homepage</a></li></ol></details></li><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Core/CSS_layout">CSS layout</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Core/CSS_layout/Introduction">Introduction to CSS layout</a></li><li><a href="/en-US/docs/Learn_web_development/Core/CSS_layout/Floats">Floats</a></li><li><a href="/en-US/docs/Learn_web_development/Core/CSS_layout/Positioning">Positioning</a></li><li><a href="/en-US/docs/Learn_web_development/Core/CSS_layout/Flexbox">Flexbox</a></li><li><a href="/en-US/docs/Learn_web_development/Core/CSS_layout/Grids">CSS grid layout</a></li><li><a href="/en-US/docs/Learn_web_development/Core/CSS_layout/Responsive_Design">Responsive design</a></li><li><a href="/en-US/docs/Learn_web_development/Core/CSS_layout/Media_queries">Media query fundamentals</a></li><li><a href="/en-US/docs/Learn_web_development/Core/CSS_layout/Fundamental_Layout_Comprehension">Challenge: Fundamental layout comprehension</a></li></ol></details></li><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Core/Scripting">Dynamic scripting with JavaScript</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/What_is_JavaScript">What is JavaScript?</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/A_first_splash">A first splash into JavaScript</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/What_went_wrong">What went wrong? Troubleshooting JavaScript</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/Variables">Storing the information you need — Variables</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/Math">Basic math in JavaScript — numbers and operators</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/Strings">Handling text — strings in JavaScript</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/Useful_string_methods">Useful string methods</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/Arrays">Arrays</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/Silly_story_generator">Challenge: Silly story generator</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/Conditionals">Making decisions in your code — conditionals</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/Loops">Looping code</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/Functions">Functions — reusable blocks of code</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/Build_your_own_function">Build your own function</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/Return_values">Function return values</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/Events">Introduction to events</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/Event_bubbling">Event bubbling</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/Image_gallery">Challenge: Image gallery</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/Object_basics">JavaScript object basics</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/DOM_scripting">DOM scripting introduction</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/Network_requests">Making network requests with JavaScript</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/JSON">Working with JSON</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Scripting/Debugging_JavaScript">Debugging JavaScript and handling errors</a></li></ol></details></li><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Core/Frameworks_libraries">JavaScript frameworks and libraries</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Core/Frameworks_libraries/Introduction">Introduction to client-side frameworks</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Frameworks_libraries/Main_features">Framework main features</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Frameworks_libraries/React_getting_started">Getting started with React</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Frameworks_libraries/React_todo_list_beginning">Beginning our React todo list</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Frameworks_libraries/React_components">Componentizing our React app</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Frameworks_libraries/React_interactivity_events_state">React interactivity: Events and state</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Frameworks_libraries/React_interactivity_filtering_conditional_rendering">React interactivity: Editing, filtering, conditional rendering</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Frameworks_libraries/React_accessibility">Accessibility in React</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Frameworks_libraries/React_resources">React resources</a></li></ol></details></li><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Core/Accessibility">Accessibility</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Core/Accessibility/What_is_accessibility">What is accessibility?</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Accessibility/Tooling">Accessibility tooling and assistive technology</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Accessibility/HTML">HTML: A good basis for accessibility</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Accessibility/CSS_and_JavaScript">CSS and JavaScript accessibility best practices</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Accessibility/WAI-ARIA_basics">WAI-ARIA basics</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Accessibility/Multimedia">Accessible multimedia</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Accessibility/Mobile">Mobile accessibility</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Accessibility/Accessibility_troubleshooting">Challenge: Accessibility troubleshooting</a></li></ol></details></li><li><a href="/en-US/docs/Learn_web_development/Core/Design_for_developers">Design for developers</a></li><li><a href="/en-US/docs/Learn_web_development/Core/Version_control">Version control</a></li><li class="section"><a href="/en-US/docs/Learn_web_development/Extensions">Extension modules</a></li><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Extensions/Advanced_JavaScript_objects">Advanced JavaScript objects</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Extensions/Advanced_JavaScript_objects/Object_prototypes">Object prototypes</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Advanced_JavaScript_objects/Object-oriented_programming">Object-oriented programming</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Advanced_JavaScript_objects/Classes_in_JavaScript">Classes in JavaScript</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Advanced_JavaScript_objects/Object_building_practice">Object building practice</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Advanced_JavaScript_objects/Adding_bouncing_balls_features">Challenge: Adding features to our bouncing balls demo</a></li></ol></details></li><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Extensions/Client-side_APIs">Client-side web APIs</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Extensions/Client-side_APIs/Introduction">Introduction to web APIs</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Client-side_APIs/Video_and_audio_APIs">Video and Audio APIs</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Client-side_APIs/Drawing_graphics">Drawing graphics</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Client-side_APIs/Client-side_storage">Client-side storage</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Client-side_APIs/Third_party_APIs">Third-party APIs</a></li></ol></details></li><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Extensions/Async_JS">Asynchronous JavaScript</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Extensions/Async_JS/Introducing">Introducing asynchronous JavaScript</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Async_JS/Promises">How to use promises</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Async_JS/Implementing_a_promise-based_API">How to implement a promise-based API</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Async_JS/Introducing_workers">Introducing workers</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Async_JS/Sequencing_animations">Challenge: Sequencing animations</a></li></ol></details></li><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Extensions/Forms">Web forms</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Extensions/Forms/Your_first_form">Your first form</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Forms/How_to_structure_a_web_form">How to structure a web form</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Forms/Basic_native_form_controls">Basic native form controls</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Forms/HTML5_input_types">The HTML5 input types</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Forms/Other_form_controls">Other form controls</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Forms/Styling_web_forms">Styling web forms</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Forms/Advanced_form_styling">Advanced form styling</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Forms/UI_pseudo-classes">UI pseudo-classes</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Forms/Form_validation">Client-side form validation</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Forms/Sending_and_retrieving_form_data">Sending form data</a></li></ol></details></li><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Extensions/Client-side_tools">Understanding client-side tools</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Extensions/Client-side_tools/Overview">Client-side tooling overview</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Client-side_tools/Package_management">Package management basics</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Client-side_tools/Introducing_complete_toolchain">Introducing a complete toolchain</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Client-side_tools/Deployment">Deploying our app</a></li></ol></details></li><li class="toggle"><details open=""><summary><a href="/en-US/docs/Learn_web_development/Extensions/Server-side">Server-side websites</a></summary><ol><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/First_steps">Server-side first steps</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/First_steps/Introduction">Introduction to the server side</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/First_steps/Client-Server_overview">Client-Server Overview</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/First_steps/Web_frameworks">Server-side web frameworks</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/First_steps/Website_security">Website security</a></li></ol></details></li><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Django">Django web framework (Python)</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Introduction">Django introduction</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Django/development_environment">Setting up a Django development environment</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Tutorial_local_library_website">Django Tutorial: The Local Library website</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Django/skeleton_website">Django Tutorial Part 2: Creating a skeleton website</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Models">Django Tutorial Part 3: Using models</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Admin_site">Django Tutorial Part 4: Django admin site</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Home_page">Django Tutorial Part 5: Creating our home page</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Generic_views">Django Tutorial Part 6: Generic list and detail views</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Sessions">Django Tutorial Part 7: Sessions framework</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Authentication">Django Tutorial Part 8: User authentication and permissions</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Forms">Django Tutorial Part 9: Working with forms</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Testing">Django Tutorial Part 10: Testing a Django web application</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Deployment">Django Tutorial Part 11: Deploying Django to production</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Django/web_application_security">Django web application security</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Django/django_assessment_blog">Assessment: DIY Django mini blog</a></li></ol></details></li><li class="toggle"><details open=""><summary><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs">Express web framework (Node.js)</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Introduction">Express/Node introduction</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/development_environment">Setting up a Node development environment</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Tutorial_local_library_website">Express Tutorial: The Local Library website</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/skeleton_website">Express Tutorial Part 2: Creating a skeleton website</a></li><li><em><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose" aria-current="page">Express Tutorial Part 3: Using a Database (with Mongoose)</a></em></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/routes">Express Tutorial Part 4: Routes and controllers</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/deployment">Express Tutorial Part 7: Deploying to production</a></li></ol></details></li></ol></details></li><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Extensions/Performance">Web performance</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Extensions/Performance/why_web_performance">The "why" of web performance</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Performance/What_is_web_performance">What is web performance?</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Performance/Perceived_performance">Perceived performance</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Performance/Measuring_performance">Measuring performance</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Performance/Multimedia">Multimedia: Images</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Performance/video">Multimedia: video</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Performance/JavaScript">JavaScript performance optimization</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Performance/HTML">HTML performance optimization</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Performance/CSS">CSS performance optimization</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Performance/business_case_for_performance">The business case for web performance</a></li></ol></details></li><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Extensions/Testing">Testing</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Extensions/Testing/Introduction">Introduction to cross-browser testing</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Testing/Testing_strategies">Strategies for carrying out testing</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Testing/HTML_and_CSS">Handling common HTML and CSS problems</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Testing/Feature_detection">Implementing feature detection</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Testing/Automated_testing">Introduction to automated testing</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Testing/Your_own_automation_environment">Setting up your own test automation environment</a></li></ol></details></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Transform_animate">Transform and animate CSS</a></li><li><a href="/en-US/docs/Learn_web_development/Extensions/Security_privacy">Security and privacy</a></li><li class="section">Further resources</li><li class="toggle"><details><summary><a href="/en-US/docs/Learn_web_development/Howto">How to solve common problems</a></summary><ol><li><a href="/en-US/docs/Learn_web_development/Howto/Solve_HTML_problems">Solve common HTML problems</a></li><li><a href="/en-US/docs/Learn_web_development/Howto/Solve_CSS_problems">Solve common CSS problems</a></li><li><a href="/en-US/docs/Learn_web_development/Howto/Solve_JavaScript_problems">Solve common JavaScript problems</a></li><li><a href="/en-US/docs/Learn_web_development/Howto/Web_mechanics">Web mechanics</a></li><li><a href="/en-US/docs/Learn_web_development/Howto/Tools_and_setup">Tools and setup</a></li><li><a href="/en-US/docs/Learn_web_development/Howto/Design_and_accessibility">Design and accessibility</a></li></ol></details></li><li><a href="/en-US/docs/Learn_web_development/About">About</a></li><li><a href="/en-US/docs/Learn_web_development/Educators">Resources for educators</a></li><li><a href="/en-US/docs/Learn_web_development/Changelog">Changelog</a></li></ol></div></div><section class="place side"></section></nav></aside><div class="toc-container"><aside class="toc"><nav><div class="document-toc-container"><section class="document-toc"><header><h2 class="document-toc-heading">In this article</h2></header><ul class="document-toc-list"><li class="document-toc-item "><a class="document-toc-link" href="#overview">Overview</a></li><li class="document-toc-item "><a class="document-toc-link" href="#designing_the_locallibrary_models">Designing the LocalLibrary models</a></li><li class="document-toc-item "><a class="document-toc-link" href="#mongoose_primer">Mongoose primer</a></li><li class="document-toc-item "><a class="document-toc-link" href="#setting_up_the_mongodb_database">Setting up the MongoDB database</a></li><li class="document-toc-item "><a class="document-toc-link" href="#install_mongoose">Install Mongoose</a></li><li class="document-toc-item "><a class="document-toc-link" href="#connect_to_mongodb">Connect to MongoDB</a></li><li class="document-toc-item "><a class="document-toc-link" href="#defining_the_locallibrary_schema">Defining the LocalLibrary Schema</a></li><li class="document-toc-item "><a class="document-toc-link" href="#testing_—_create_some_items">Testing — create some items</a></li><li class="document-toc-item "><a class="document-toc-link" href="#summary">Summary</a></li><li class="document-toc-item "><a class="document-toc-link" href="#see_also">See also</a></li></ul></section></div></nav></aside><section class="place side"></section></div></div><main id="content" class="main-content "><article class="main-page-content" lang="en-US"><header><h1>Express Tutorial Part 3: Using a Database (with Mongoose)</h1></header><div class="section-content"><ul class="prev-next"><li><a class="button secondary" href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/skeleton_website"><span class="button-wrap"> Previous </span></a></li><li><a class="button secondary" href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs"><span class="button-wrap"> Overview: Express web framework (Node.js/JavaScript)</span></a></li><li><a class="button secondary" href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/routes"><span class="button-wrap"> Next </span></a></li></ul> <p>This article briefly introduces databases, and how to use them with Node/Express apps. It then goes on to show how we can use <a href="https://mongoosejs.com/" class="external" target="_blank">Mongoose</a> to provide database access for the <a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Tutorial_local_library_website">LocalLibrary</a> website. It explains how object schema and models are declared, the main field types, and basic validation. It also briefly shows a few of the main ways in which you can access model data.</p> <figure class="table-container"><table> <tbody> <tr> <th scope="row">Prerequisites:</th> <td> <a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/skeleton_website">Express Tutorial Part 2: Creating a skeleton website</a> </td> </tr> <tr> <th scope="row">Objective:</th> <td>To be able to design and create your own models using Mongoose.</td> </tr> </tbody> </table></figure></div><section aria-labelledby="overview"><h2 id="overview"><a href="#overview">Overview</a></h2><div class="section-content"><p>Library staff will use the Local Library website to store information about books and borrowers, while library members will use it to browse and search for books, find out whether there are any copies available, and then reserve or borrow them. In order to store and retrieve information efficiently, we will store it in a <em>database</em>.</p> <p>Express apps can use many different databases, and there are several approaches you can use for performing <strong>C</strong>reate, <strong>R</strong>ead, <strong>U</strong>pdate and <strong>D</strong>elete (CRUD) operations. This tutorial provides a brief overview of some of the available options and then goes on to show in detail the particular mechanisms selected.</p></div></section><section aria-labelledby="what_databases_can_i_use"><h3 id="what_databases_can_i_use"><a href="#what_databases_can_i_use">What databases can I use?</a></h3><div class="section-content"><p><em>Express</em> apps can use any database supported by <em>Node</em> (<em>Express</em> itself doesn't define any specific additional behavior/requirements for database management). There are <a href="https://expressjs.com/en/guide/database-integration.html" class="external" target="_blank">many popular options</a>, including PostgreSQL, MySQL, Redis, SQLite, and MongoDB.</p> <p>When choosing a database, you should consider things like time-to-productivity/learning curve, performance, ease of replication/backup, cost, community support, etc. While there is no single "best" database, almost any of the popular solutions should be more than acceptable for a small-to-medium-sized site like our Local Library.</p> <p>For more information on the options see <a href="https://expressjs.com/en/guide/database-integration.html" class="external" target="_blank">Database integration</a> (Express docs).</p></div></section><section aria-labelledby="what_is_the_best_way_to_interact_with_a_database"><h3 id="what_is_the_best_way_to_interact_with_a_database"><a href="#what_is_the_best_way_to_interact_with_a_database">What is the best way to interact with a database?</a></h3><div class="section-content"><p>There are two common approaches for interacting with a database:</p> <ul> <li>Using the databases' native query language, such as SQL.</li> <li>Using an Object Relational Mapper ("ORM"). An ORM represents the website's data as JavaScript objects, which are then mapped to the underlying database. Some ORMs are tied to a specific database, while others provide a database-agnostic backend.</li> </ul> <p>The very best <em>performance</em> can be gained by using SQL, or whatever query language is supported by the database. ODM's are often slower because they use translation code to map between objects and the database format, which may not use the most efficient database queries (this is particularly true if the ODM supports different database backends, and must make greater compromises in terms of what database features are supported).</p> <p>The benefit of using an ORM is that programmers can continue to think in terms of JavaScript objects rather than database semantics — this is particularly true if you need to work with different databases (on either the same or different websites). They also provide an obvious place to perform data validation.</p> <div class="notecard note"> <p><strong>Note:</strong> Using ODM/ORMs often results in lower costs for development and maintenance! Unless you're very familiar with the native query language or performance is paramount, you should strongly consider using an ODM.</p> </div></div></section><section aria-labelledby="what_ormodm_should_i_use"><h3 id="what_ormodm_should_i_use"><a href="#what_ormodm_should_i_use">What ORM/ODM should I use?</a></h3><div class="section-content"><p>There are many ODM/ORM solutions available on the npm package manager site (check out the <a href="https://www.npmjs.com/search?q=keywords:odm" class="external" target="_blank">odm</a> and <a href="https://www.npmjs.com/search?q=keywords:orm" class="external" target="_blank">orm</a> tags for a subset!).</p> <p>A few solutions that were popular at the time of writing are:</p> <ul> <li><a href="https://www.npmjs.com/package/mongoose" class="external" target="_blank">Mongoose</a>: Mongoose is a <a href="https://www.mongodb.com/" class="external" target="_blank">MongoDB</a> object modeling tool designed to work in an asynchronous environment.</li> <li><a href="https://www.npmjs.com/package/waterline" class="external" target="_blank">Waterline</a>: An ORM extracted from the Express-based <a href="https://sailsjs.com/" class="external" target="_blank">Sails</a> web framework. It provides a uniform API for accessing numerous different databases, including Redis, MySQL, LDAP, MongoDB, and Postgres.</li> <li><a href="https://www.npmjs.com/package/bookshelf" class="external" target="_blank">Bookshelf</a>: Features both promise-based and traditional callback interfaces, providing transaction support, eager/nested-eager relation loading, polymorphic associations, and support for one-to-one, one-to-many, and many-to-many relations. Works with PostgreSQL, MySQL, and SQLite3.</li> <li><a href="https://www.npmjs.com/package/objection" class="external" target="_blank">Objection</a>: Makes it as easy as possible to use the full power of SQL and the underlying database engine (supports SQLite3, Postgres, and MySQL).</li> <li><a href="https://www.npmjs.com/package/sequelize" class="external" target="_blank">Sequelize</a> is a promise-based ORM for Node.js and io.js. It supports the dialects PostgreSQL, MySQL, MariaDB, SQLite, and MSSQL and features solid transaction support, relations, read replication and more.</li> <li><a href="https://node-orm.readthedocs.io/en/latest/" class="external" target="_blank">Node ORM2</a> is an Object Relationship Manager for NodeJS. It supports MySQL, SQLite, and Postgres, helping to work with the database using an object-oriented approach.</li> <li><a href="https://graphql.org/" class="external" target="_blank">GraphQL</a>: Primarily a query language for restful APIs, GraphQL is very popular, and has features available for reading data from databases.</li> </ul> <p>As a general rule, you should consider both the features provided and the "community activity" (downloads, contributions, bug reports, quality of documentation, etc.) when selecting a solution. At the time of writing Mongoose is by far the most popular ODM, and is a reasonable choice if you're using MongoDB for your database.</p></div></section><section aria-labelledby="using_mongoose_and_mongodb_for_the_locallibrary"><h3 id="using_mongoose_and_mongodb_for_the_locallibrary"><a href="#using_mongoose_and_mongodb_for_the_locallibrary">Using Mongoose and MongoDB for the LocalLibrary</a></h3><div class="section-content"><p>For the <em>Local Library</em> example (and the rest of this topic) we're going to use the <a href="https://www.npmjs.com/package/mongoose" class="external" target="_blank">Mongoose ODM</a> to access our library data. Mongoose acts as a front end to <a href="https://www.mongodb.com/company/what-is-mongodb" class="external" target="_blank">MongoDB</a>, an open source <a href="https://en.wikipedia.org/wiki/NoSQL" class="external" target="_blank">NoSQL</a> database that uses a document-oriented data model. A "collection" of "documents" in a MongoDB database <a href="https://www.mongodb.com/docs/manual/core/databases-and-collections/" class="external" target="_blank">is analogous to</a> a "table" of "rows" in a relational database.</p> <p>This ODM and database combination is extremely popular in the Node community, partially because the document storage and query system looks very much like JSON, and is hence familiar to JavaScript developers.</p> <div class="notecard note"> <p><strong>Note:</strong> You don't need to know MongoDB in order to use Mongoose, although parts of the <a href="https://mongoosejs.com/docs/guide.html" class="external" target="_blank">Mongoose documentation</a> <em>are</em> easier to use and understand if you are already familiar with MongoDB.</p> </div> <p>The rest of this tutorial shows how to define and access the Mongoose schema and models for the <a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Tutorial_local_library_website">LocalLibrary website</a> example.</p></div></section><section aria-labelledby="designing_the_locallibrary_models"><h2 id="designing_the_locallibrary_models"><a href="#designing_the_locallibrary_models">Designing the LocalLibrary models</a></h2><div class="section-content"><p>Before you jump in and start coding the models, it's worth taking a few minutes to think about what data we need to store and the relationships between the different objects.</p> <p>We know that we need to store information about books (title, summary, author, genre, ISBN) and that we might have multiple copies available (with globally unique ids, availability statuses, etc.). We might need to store more information about the author than just their name, and there might be multiple authors with the same or similar names. We want to be able to sort information based on the book title, author, genre, and category.</p> <p>When designing your models it makes sense to have separate models for every "object" (a group of related information). In this case some obvious candidates for these models are books, book instances, and authors.</p> <p>You might also want to use models to represent selection-list options (e.g. like a drop-down list of choices), rather than hard-coding the choices into the website itself — this is recommended when all the options aren't known up front or may change. A good example is a genre (e.g. fantasy, science fiction, etc.).</p> <p>Once we've decided on our models and fields, we need to think about the relationships between them.</p> <p>With that in mind, the UML association diagram below shows the models we'll define in this case (as boxes). As discussed above, we've created models for the book (the generic details of the book), book instance (status of specific physical copies of the book available in the system), and author. We have also decided to have a model for the genre so that values can be created dynamically. We've decided not to have a model for the <code>BookInstance:status</code> — we will hard code the acceptable values because we don't expect these to change. Within each of the boxes, you can see the model name, the field names and types, and also the methods and their return types.</p> <p>The diagram also shows the relationships between the models, including their <em>multiplicities</em>. The multiplicities are the numbers on the diagram showing the numbers (maximum and minimum) of each model that may be present in the relationship. For example, the connecting line between the boxes shows that <code>Book</code> and a <code>Genre</code> are related. The numbers close to the <code>Book</code> model show that a <code>Genre</code> must have zero or more <code>Book</code>s (as many as you like), while the numbers on the other end of the line next to the <code>Genre</code> show that a book can have zero or more associated <code>Genre</code>s.</p> <div class="notecard note"> <p><strong>Note:</strong> As discussed in our <a href="#mongoose_primer">Mongoose primer</a> below it is often better to have the field that defines the relationship between the documents/models in just <em>one</em> model (you can still find the reverse relationship by searching for the associated <code>_id</code> in the other model). Below we have chosen to define the relationship between <code>Book</code>/<code>Genre</code> and <code>Book</code>/<code>Author</code> in the Book schema, and the relationship between the <code>Book</code>/<code>BookInstance</code> in the <code>BookInstance</code> Schema. This choice was somewhat arbitrary — we could equally well have had the field in the other schema.</p> </div> <p><img src="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/library_website_-_mongoose_express.png" alt="Mongoose Library Model with correct cardinality" width="737" height="620" loading="lazy"></p> <div class="notecard note"> <p><strong>Note:</strong> The next section provides a basic primer explaining how models are defined and used. As you read it, consider how we will construct each of the models in the diagram above.</p> </div></div></section><section aria-labelledby="database_apis_are_asynchronous"><h3 id="database_apis_are_asynchronous"><a href="#database_apis_are_asynchronous">Database APIs are asynchronous</a></h3><div class="section-content"><p>Database methods to create, find, update, or delete records are asynchronous. What this means is that the methods return immediately, and the code to handle the success or failure of the method runs at a later time when the operation completes. Other code can execute while the server is waiting for the database operation to complete, so the server can remain responsive to other requests.</p> <p>JavaScript has a number of mechanisms for supporting asynchronous behavior. Historically JavaScript relied heavily on passing <a href="/en-US/docs/Learn_web_development/Extensions/Async_JS/Introducing">callback functions</a> to asynchronous methods to handle the success and error cases. In modern JavaScript callbacks have largely been replaced by <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a>. Promises are objects that are (immediately) returned by an asynchronous method that represent its future state. When the operation completes, the promise object is "settled", and resolves an object that represents the result of the operation or an error.</p> <p>There are two main ways you can use promises to run code when a promise is settled, and we highly recommend that you read <a href="/en-US/docs/Learn_web_development/Extensions/Async_JS/Promises">How to use promises</a> for a high level overview of both approaches. In this tutorial, we'll primarily be using <a href="/en-US/docs/Web/JavaScript/Reference/Operators/await"><code>await</code></a> to wait on promise completion within an <a href="/en-US/docs/Web/JavaScript/Reference/Statements/async_function"><code>async function</code></a>, because this leads to more readable and understandable asynchronous code.</p> <p>The way this approach works is that you use the <code>async function</code> keyword to mark a function as asynchronous, and then inside that function apply <code>await</code> to any method that returns a promise. When the asynchronous function is executed its operation is paused at the first <code>await</code> method until the promise settles. From the perspective of the surrounding code the asynchronous function then returns and the code after it is able to run. Later when the promise settles, the <code>await</code> method inside the asynchronous function returns with the result, or an error is thrown if the promise was rejected. The code in the asynchronous function then executes until either another <code>await</code> is encountered, at which point it will pause again, or until all the code in the function has been run.</p> <p>You can see how this works in the example below. <code>myFunction()</code> is an asynchronous function that is called within a <a href="/en-US/docs/Web/JavaScript/Reference/Statements/try...catch"><code>try...catch</code></a> block. When <code>myFunction()</code> is run, code execution is paused at <code>methodThatReturnsPromise()</code> until the promise resolves, at which point the code continues to <code>aFunctionThatReturnsPromise()</code> and waits again. The code in the <code>catch</code> block runs if an error is thrown in the asynchronous function, and this will happen if the promise returned by either of the methods is rejected.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>async function myFunction { // ... await someObject.methodThatReturnsPromise(); // ... await aFunctionThatReturnsPromise(); // ... } try { // ... myFunction(); // ... } catch (e) { // error handling code } </code></pre></div> <p>The asynchronous methods above are run in sequence. If the methods don't depend on each other then you can run them in parallel and finish the whole operation more quickly. This is done using the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all"><code>Promise.all()</code></a> method, which takes an iterable of promises as input and returns a single <code>Promise</code>. This returned promise fulfills when all of the input's promises fulfill, with an array of the fulfillment values. It rejects when any of the input's promises rejects, with this first rejection reason.</p> <p>The code below shows how this works. First, we have two functions that return promises. We <code>await</code> on both of them to complete using the promise returned by <code>Promise.all()</code>. Once they both complete <code>await</code> returns and the results array is populated, the function then continues to the next <code>await</code>, and waits until the promise returned by <code>anotherFunctionThatReturnsPromise()</code> is settled. You would call the <code>myFunction()</code> in a <code>try...catch</code> block to catch any errors.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>async function myFunction { // ... const [resultFunction1, resultFunction2] = await Promise.all([ functionThatReturnsPromise1(), functionThatReturnsPromise2() ]); // ... await anotherFunctionThatReturnsPromise(resultFunction1); } </code></pre></div> <p>Promises with <code>await</code>/<code>async</code> allow both flexible and "comprehensible" control over asynchronous execution!</p></div></section><section aria-labelledby="mongoose_primer"><h2 id="mongoose_primer"><a href="#mongoose_primer">Mongoose primer</a></h2><div class="section-content"><p>This section provides an overview of how to connect Mongoose to a MongoDB database, how to define a schema and a model, and how to make basic queries.</p> <div class="notecard note"> <p><strong>Note:</strong> This primer is heavily influenced by the <a href="https://www.npmjs.com/package/mongoose" class="external" target="_blank">Mongoose quick start</a> on <em>npm</em> and the <a href="https://mongoosejs.com/docs/guide.html" class="external" target="_blank">official documentation</a>.</p> </div></div></section><section aria-labelledby="installing_mongoose_and_mongodb"><h3 id="installing_mongoose_and_mongodb"><a href="#installing_mongoose_and_mongodb">Installing Mongoose and MongoDB</a></h3><div class="section-content"><p>Mongoose is installed in your project (<strong>package.json</strong>) like any other dependency — using npm. To install it, use the following command inside your project folder:</p> <div class="code-example"><div class="example-header"><span class="language-name">bash</span></div><pre class="brush: bash notranslate"><code>npm install mongoose </code></pre></div> <p>Installing <em>Mongoose</em> adds all its dependencies, including the MongoDB database driver, but it does not install MongoDB itself. If you want to install a MongoDB server then you can <a href="https://www.mongodb.com/try/download/community" class="external" target="_blank">download installers from here</a> for various operating systems and install it locally. You can also use cloud-based MongoDB instances.</p> <div class="notecard note"> <p><strong>Note:</strong> For this tutorial, we'll be using the <a href="https://www.mongodb.com/" class="external" target="_blank">MongoDB Atlas</a> cloud-based <em>database as a service</em> free tier to provide the database. This is suitable for development and makes sense for the tutorial because it makes "installation" operating system independent (database-as-a-service is also one approach you might use for your production database).</p> </div></div></section><section aria-labelledby="connecting_to_mongodb"><h3 id="connecting_to_mongodb"><a href="#connecting_to_mongodb">Connecting to MongoDB</a></h3><div class="section-content"><p><em>Mongoose</em> requires a connection to a MongoDB database. You can <code>require()</code> and connect to a locally hosted database with <code>mongoose.connect()</code> as shown below (for the tutorial we'll instead connect to an internet-hosted database).</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>// Import the mongoose module const mongoose = require("mongoose"); // Set `strictQuery: false` to globally opt into filtering by properties that aren't in the schema // Included because it removes preparatory warnings for Mongoose 7. // See: https://mongoosejs.com/docs/migrating_to_6.html#strictquery-is-removed-and-replaced-by-strict mongoose.set("strictQuery", false); // Define the database URL to connect to. const mongoDB = "mongodb://127.0.0.1/my_database"; // Wait for database to connect, logging an error if there is a problem main().catch((err) =&gt; console.log(err)); async function main() { await mongoose.connect(mongoDB); } </code></pre></div> <div class="notecard note"> <p><strong>Note:</strong> As discussed in the <a href="#database_apis_are_asynchronous">Database APIs are asynchronous</a> section, here we <code>await</code> on the promise returned by the <code>connect()</code> method within an <code>async</code> function. We use the promise <code>catch()</code> handler to handle any errors when trying to connect, but we might also have called <code>main()</code> within a <code>try...catch</code> block.</p> </div> <p>You can get the default <code>Connection</code> object with <code>mongoose.connection</code>. If you need to create additional connections you can use <code>mongoose.createConnection()</code>. This takes the same form of database URI (with host, database, port, options, etc.) as <code>connect()</code> and returns a <code>Connection</code> object). Note that <code>createConnection()</code> returns immediately; if you need to wait on the connection to be established you can call it with <code>asPromise()</code> to return a promise (<code>mongoose.createConnection(mongoDB).asPromise()</code>).</p></div></section><section aria-labelledby="defining_and_creating_models"><h3 id="defining_and_creating_models"><a href="#defining_and_creating_models">Defining and creating models</a></h3><div class="section-content"><p>Models are <em>defined</em> using the <code>Schema</code> interface. The Schema allows you to define the fields stored in each document along with their validation requirements and default values. In addition, you can define static and instance helper methods to make it easier to work with your data types, and also virtual properties that you can use like any other field, but which aren't actually stored in the database (we'll discuss a bit further below).</p> <p>Schemas are then "compiled" into models using the <code>mongoose.model()</code> method. Once you have a model you can use it to find, create, update, and delete objects of the given type.</p> <div class="notecard note"> <p><strong>Note:</strong> Each model maps to a <em>collection</em> of <em>documents</em> in the MongoDB database. The documents will contain the fields/schema types defined in the model <code>Schema</code>.</p> </div> <h4 id="defining_schemas">Defining schemas</h4> <p>The code fragment below shows how you might define a simple schema. First you <code>require()</code> mongoose, then use the Schema constructor to create a new schema instance, defining the various fields inside it in the constructor's object parameter.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>// Require Mongoose const mongoose = require("mongoose"); // Define a schema const Schema = mongoose.Schema; const SomeModelSchema = new Schema({ a_string: String, a_date: Date, }); </code></pre></div> <p>In the case above we just have two fields, a string and a date. In the next sections, we will show some of the other field types, validation, and other methods.</p> <h4 id="creating_a_model">Creating a model</h4> <p>Models are created from schemas using the <code>mongoose.model()</code> method:</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>// Define schema const Schema = mongoose.Schema; const SomeModelSchema = new Schema({ a_string: String, a_date: Date, }); // Compile model from schema const SomeModel = mongoose.model("SomeModel", SomeModelSchema); </code></pre></div> <p>The first argument is the singular name of the collection that will be created for your model (Mongoose will create the database collection for the model <em>SomeModel</em> above), and the second argument is the schema you want to use in creating the model.</p> <div class="notecard note"> <p><strong>Note:</strong> Once you've defined your model classes you can use them to create, update, or delete records, and run queries to get all records or particular subsets of records. We'll show you how to do this in the <a href="#using_models">Using models</a> section, and when we create our views.</p> </div> <h4 id="schema_types_fields">Schema types (fields)</h4> <p>A schema can have an arbitrary number of fields — each one represents a field in the documents stored in <em>MongoDB</em>. An example schema showing many of the common field types and how they are declared is shown below.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>const schema = new Schema({ name: String, binary: Buffer, living: Boolean, updated: { type: Date, default: Date.now() }, age: { type: Number, min: 18, max: 65, required: true }, mixed: Schema.Types.Mixed, _someId: Schema.Types.ObjectId, array: [], ofString: [String], // You can also have an array of each of the other types too. nested: { stuff: { type: String, lowercase: true, trim: true } }, }); </code></pre></div> <p>Most of the <a href="https://mongoosejs.com/docs/schematypes.html" class="external" target="_blank">SchemaTypes</a> (the descriptors after "type:" or after field names) are self-explanatory. The exceptions are:</p> <ul> <li><code>ObjectId</code>: Represents specific instances of a model in the database. For example, a book might use this to represent its author object. This will actually contain the unique ID (<code>_id</code>) for the specified object. We can use the <code>populate()</code> method to pull in the associated information when needed.</li> <li><a href="https://mongoosejs.com/docs/schematypes.html#mixed" class="external" target="_blank"><code>Mixed</code></a>: An arbitrary schema type.</li> <li><code>[]</code>: An array of items. You can perform JavaScript array operations on these models (push, pop, unshift, etc.). The examples above show an array of objects without a specified type and an array of <code>String</code> objects, but you can have an array of any type of object.</li> </ul> <p>The code also shows both ways of declaring a field:</p> <ul> <li> <p>Field <em>name</em> and <em>type</em> as a key-value pair (i.e. as done with fields <code>name</code>, <code>binary</code> and <code>living</code>).</p> </li> <li> <p>Field <em>name</em> followed by an object defining the <code>type</code>, and any other <em>options</em> for the field. Options include things like:</p> <ul> <li>default values.</li> <li>built-in validators (e.g. max/min values) and custom validation functions.</li> <li>Whether the field is required</li> <li>Whether <code>String</code> fields should automatically be set to lowercase, uppercase, or trimmed (e.g. <code>{ type: String, lowercase: true, trim: true }</code>)</li> </ul> </li> </ul> <p>For more information about options see <a href="https://mongoosejs.com/docs/schematypes.html" class="external" target="_blank">SchemaTypes</a> (Mongoose docs).</p> <h4 id="validation">Validation</h4> <p>Mongoose provides built-in and custom validators, and synchronous and asynchronous validators. It allows you to specify both the acceptable range of values and the error message for validation failure in all cases.</p> <p>The built-in validators include:</p> <ul> <li> <p>All <a href="https://mongoosejs.com/docs/schematypes.html" class="external" target="_blank">SchemaTypes</a> have the built-in <a href="https://mongoosejs.com/docs/api.html#schematype_SchemaType-required" class="external" target="_blank">required</a> validator. This is used to specify whether the field must be supplied in order to save a document.</p> </li> <li> <p><a href="https://mongoosejs.com/docs/api/schemanumber.html" class="external" target="_blank">Numbers</a> have <a href="https://mongoosejs.com/docs/api/schemanumber.html#SchemaNumber.prototype.min()" class="external" target="_blank">min</a> and <a href="https://mongoosejs.com/docs/api/schemanumber.html#SchemaNumber.prototype.max()" class="external" target="_blank">max</a> validators.</p> </li> <li> <p><a href="https://mongoosejs.com/docs/api/schemastring.html" class="external" target="_blank">Strings</a> have:</p> <ul> <li><a href="https://mongoosejs.com/docs/api/schemastring.html#SchemaString.prototype.enum()" class="external" target="_blank">enum</a>: specifies the set of allowed values for the field.</li> <li><a href="https://mongoosejs.com/docs/api/schemastring.html#SchemaString.prototype.match()" class="external" target="_blank">match</a>: specifies a regular expression that the string must match.</li> <li><a href="https://mongoosejs.com/docs/api/schemastring.html#SchemaString.prototype.maxlength()" class="external" target="_blank">maxLength</a> and <a href="https://mongoosejs.com/docs/api/schemastring.html#SchemaString.prototype.minlength()" class="external" target="_blank">minLength</a> for the string.</li> </ul> </li> </ul> <p>The example below (slightly modified from the Mongoose documents) shows how you can specify some of the validator types and error messages:</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>const breakfastSchema = new Schema({ eggs: { type: Number, min: [6, "Too few eggs"], max: 12, required: [true, "Why no eggs?"], }, drink: { type: String, enum: ["Coffee", "Tea", "Water"], }, }); </code></pre></div> <p>For complete information on field validation see <a href="https://mongoosejs.com/docs/validation.html" class="external" target="_blank">Validation</a> (Mongoose docs).</p> <h4 id="virtual_properties">Virtual properties</h4> <p>Virtual properties are document properties that you can get and set but that do not get persisted to MongoDB. The getters are useful for formatting or combining fields, while setters are useful for de-composing a single value into multiple values for storage. The example in the documentation constructs (and deconstructs) a full name virtual property from a first and last name field, which is easier and cleaner than constructing a full name every time one is used in a template.</p> <div class="notecard note"> <p><strong>Note:</strong> We will use a virtual property in the library to define a unique URL for each model record using a path and the record's <code>_id</code> value.</p> </div> <p>For more information see <a href="https://mongoosejs.com/docs/guide.html#virtuals" class="external" target="_blank">Virtuals</a> (Mongoose documentation).</p> <h4 id="methods_and_query_helpers">Methods and query helpers</h4> <p>A schema can also have <a href="https://mongoosejs.com/docs/guide.html#methods" class="external" target="_blank">instance methods</a>, <a href="https://mongoosejs.com/docs/guide.html#statics" class="external" target="_blank">static methods</a>, and <a href="https://mongoosejs.com/docs/guide.html#query-helpers" class="external" target="_blank">query helpers</a>. The instance and static methods are similar, but with the obvious difference that an instance method is associated with a particular record and has access to the current object. Query helpers allow you to extend mongoose's <a href="https://mongoosejs.com/docs/queries.html" class="external" target="_blank">chainable query builder API</a> (for example, allowing you to add a query "byName" in addition to the <code>find()</code>, <code>findOne()</code> and <code>findById()</code> methods).</p></div></section><section aria-labelledby="using_models"><h3 id="using_models"><a href="#using_models">Using models</a></h3><div class="section-content"><p>Once you've created a schema you can use it to create models. The model represents a collection of documents in the database that you can search, while the model's instances represent individual documents that you can save and retrieve.</p> <p>We provide a brief overview below. For more information see: <a href="https://mongoosejs.com/docs/models.html" class="external" target="_blank">Models</a> (Mongoose docs).</p> <div class="notecard note"> <p><strong>Note:</strong> Creation, update, deletion and querying of records are asynchronous operations that return a <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">promise</a>. The examples below show just the use of the relevant methods and <code>await</code> (i.e. the essential code for using the methods). The surrounding <code>async function</code> and <code>try...catch</code> block to catch errors are omitted for clarity. For more information on using <code>await/async</code> see <a href="#database_apis_are_asynchronous">Database APIs are asynchronous</a> above.</p> </div> <h4 id="creating_and_modifying_documents">Creating and modifying documents</h4> <p>To create a record you can define an instance of the model and then call <a href="https://mongoosejs.com/docs/api/model.html#Model.prototype.save" class="external" target="_blank"><code>save()</code></a> on it. The examples below assume <code>SomeModel</code> is a model (with a single field <code>name</code>) that we have created from our schema.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>// Create an instance of model SomeModel const awesome_instance = new SomeModel({ name: "awesome" }); // Save the new model instance asynchronously await awesome_instance.save(); </code></pre></div> <p>You can also use <a href="https://mongoosejs.com/docs/api/model.html#Model.create" class="external" target="_blank"><code>create()</code></a> to define the model instance at the same time as you save it. Below we create just one, but you can create multiple instances by passing in an array of objects.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>await SomeModel.create({ name: "also_awesome" }); </code></pre></div> <p>Every model has an associated connection (this will be the default connection when you use <code>mongoose.model()</code>). You create a new connection and call <code>.model()</code> on it to create the documents on a different database.</p> <p>You can access the fields in this new record using the dot syntax, and change the values. You have to call <code>save()</code> or <code>update()</code> to store modified values back to the database.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>// Access model field values using dot notation console.log(awesome_instance.name); //should log 'also_awesome' // Change record by modifying the fields, then calling save(). awesome_instance.name = "New cool name"; await awesome_instance.save(); </code></pre></div> <h4 id="searching_for_records">Searching for records</h4> <p>You can search for records using query methods, specifying the query conditions as a JSON document. The code fragment below shows how you might find all athletes in a database that play tennis, returning just the fields for athlete <em>name</em> and <em>age</em>. Here we just specify one matching field (sport) but you can add more criteria, specify regular expression criteria, or remove the conditions altogether to return all athletes.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>const Athlete = mongoose.model("Athlete", yourSchema); // find all athletes who play tennis, returning the 'name' and 'age' fields const tennisPlayers = await Athlete.find( { sport: "Tennis" }, "name age", ).exec(); </code></pre></div> <div class="notecard note"> <p><strong>Note:</strong> It is important to remember that not finding any results is <strong>not an error</strong> for a search — but it may be a fail-case in the context of your application. If your application expects a search to find a value you can check the number of entries returned in the result.</p> </div> <p>Query APIs, such as <a href="https://mongoosejs.com/docs/api/model.html#Model.find()" class="external" target="_blank"><code>find()</code></a>, return a variable of type <a href="https://mongoosejs.com/docs/api/query.html" class="external" target="_blank">Query</a>. You can use a query object to build up a query in parts before executing it with the <a href="https://mongoosejs.com/docs/api/query.html#Query.prototype.exec" class="external" target="_blank"><code>exec()</code></a> method. <code>exec()</code> executes the query and returns a promise that you can <code>await</code> on for the result.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>// find all athletes that play tennis const query = Athlete.find({ sport: "Tennis" }); // selecting the 'name' and 'age' fields query.select("name age"); // limit our results to 5 items query.limit(5); // sort by age query.sort({ age: -1 }); // execute the query at a later time query.exec(); </code></pre></div> <p>Above we've defined the query conditions in the <a href="https://mongoosejs.com/docs/api/model.html#Model.find()" class="external" target="_blank"><code>find()</code></a> method. We can also do this using a <a href="https://mongoosejs.com/docs/api/model.html#Model.where()" class="external" target="_blank"><code>where()</code></a> function, and we can chain all the parts of our query together using the dot operator (.) rather than adding them separately. The code fragment below is the same as our query above, with an additional condition for the age.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>Athlete.find() .where("sport") .equals("Tennis") .where("age") .gt(17) .lt(50) // Additional where query .limit(5) .sort({ age: -1 }) .select("name age") .exec(); </code></pre></div> <p>The <a href="https://mongoosejs.com/docs/api/model.html#Model.find()" class="external" target="_blank"><code>find()</code></a> method gets all matching records, but often you just want to get one match. The following methods query for a single record:</p> <ul> <li><a href="https://mongoosejs.com/docs/api/model.html#Model.findById()" class="external" target="_blank"><code>findById()</code></a>: Finds the document with the specified <code>id</code> (every document has a unique <code>id</code>).</li> <li><a href="https://mongoosejs.com/docs/api/model.html#Model.findOne()" class="external" target="_blank"><code>findOne()</code></a>: Finds a single document that matches the specified criteria.</li> <li><a href="https://mongoosejs.com/docs/api/model.html#Model.findByIdAndDelete()" class="external" target="_blank"><code>findByIdAndDelete()</code></a>, <a href="https://mongoosejs.com/docs/api/model.html#Model.findByIdAndUpdate()" class="external" target="_blank"><code>findByIdAndUpdate()</code></a>, <a href="https://mongoosejs.com/docs/api/model.html#Model.findOneAndRemove()" class="external" target="_blank"><code>findOneAndRemove()</code></a>, <a href="https://mongoosejs.com/docs/api/model.html#Model.findOneAndUpdate()" class="external" target="_blank"><code>findOneAndUpdate()</code></a>: Finds a single document by <code>id</code> or criteria and either updates or removes it. These are useful convenience functions for updating and removing records.</li> </ul> <div class="notecard note"> <p><strong>Note:</strong> There is also a <a href="https://mongoosejs.com/docs/api/model.html#Model.countDocuments()" class="external" target="_blank"><code>countDocuments()</code></a> method that you can use to get the number of items that match conditions. This is useful if you want to perform a count without actually fetching the records.</p> </div> <p>There is a lot more you can do with queries. For more information see: <a href="https://mongoosejs.com/docs/queries.html" class="external" target="_blank">Queries</a> (Mongoose docs).</p> <h4 id="working_with_related_documents_—_population">Working with related documents — population</h4> <p>You can create references from one document/model instance to another using the <code>ObjectId</code> schema field, or from one document to many using an array of <code>ObjectIds</code>. The field stores the id of the related model. If you need the actual content of the associated document, you can use the <a href="https://mongoosejs.com/docs/populate.html" class="external" target="_blank"><code>populate()</code></a> method in a query to replace the id with the actual data.</p> <p>For example, the following schema defines authors and stories. Each author can have multiple stories, which we represent as an array of <code>ObjectId</code>. Each story can have a single author. The <code>ref</code> property tells the schema which model can be assigned to this field.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>const mongoose = require("mongoose"); const Schema = mongoose.Schema; const authorSchema = new Schema({ name: String, stories: [{ type: Schema.Types.ObjectId, ref: "Story" }], }); const storySchema = new Schema({ author: { type: Schema.Types.ObjectId, ref: "Author" }, title: String, }); const Story = mongoose.model("Story", storySchema); const Author = mongoose.model("Author", authorSchema); </code></pre></div> <p>We can save our references to the related document by assigning the <code>_id</code> value. Below we create an author, then a story, and assign the author id to our story's author field.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>const bob = new Author({ name: "Bob Smith" }); await bob.save(); // Bob now exists, so lets create a story const story = new Story({ title: "Bob goes sledding", author: bob._id, // assign the _id from our author Bob. This ID is created by default! }); await story.save(); </code></pre></div> <div class="notecard note"> <p><strong>Note:</strong> One great benefit of this style of programming is that we don't have to complicate the main path of our code with error checking. If any of the <code>save()</code> operations fail, the promise will reject and an error will be thrown. Our error handling code deals with that separately (usually in a <code>catch()</code> block), so the intent of our code is very clear.</p> </div> <p>Our story document now has an author referenced by the author document's ID. In order to get the author information in the story results we use <a href="https://mongoosejs.com/docs/api/model.html#Model.populate" class="external" target="_blank"><code>populate()</code></a>, as shown below.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>Story.findOne({ title: "Bob goes sledding" }) .populate("author") // Replace the author id with actual author information in results .exec(); </code></pre></div> <div class="notecard note"> <p><strong>Note:</strong> Astute readers will have noted that we added an author to our story, but we didn't do anything to add our story to our author's <code>stories</code> array. How then can we get all stories by a particular author? One way would be to add our story to the stories array, but this would result in us having two places where the information relating authors and stories needs to be maintained.</p> <p>A better way is to get the <code>_id</code> of our <em>author</em>, then use <code>find()</code> to search for this in the author field across all stories.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>Story.find({ author: bob._id }).exec(); </code></pre></div> </div> <p>This is almost everything you need to know about working with related items <em>for this tutorial</em>. For more detailed information see <a href="https://mongoosejs.com/docs/populate.html" class="external" target="_blank">Population</a> (Mongoose docs).</p></div></section><section aria-labelledby="one_schemamodel_per_file"><h3 id="one_schemamodel_per_file"><a href="#one_schemamodel_per_file">One schema/model per file</a></h3><div class="section-content"><p>While you can create schemas and models using any file structure you like, we highly recommend defining each model schema in its own module (file), then exporting the method to create the model. This is shown below:</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>// File: ./models/some-model.js // Require Mongoose const mongoose = require("mongoose"); // Define a schema const Schema = mongoose.Schema; const SomeModelSchema = new Schema({ a_string: String, a_date: Date, }); // Export function to create "SomeModel" model class module.exports = mongoose.model("SomeModel", SomeModelSchema); </code></pre></div> <p>You can then require and use the model immediately in other files. Below we show how you might use it to get all instances of the model.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>// Create a SomeModel model just by requiring the module const SomeModel = require("../models/some-model"); // Use the SomeModel object (model) to find all SomeModel records const modelInstances = await SomeModel.find().exec(); </code></pre></div></div></section><section aria-labelledby="setting_up_the_mongodb_database"><h2 id="setting_up_the_mongodb_database"><a href="#setting_up_the_mongodb_database">Setting up the MongoDB database</a></h2><div class="section-content"><p>Now that we understand something of what Mongoose can do and how we want to design our models, it's time to start work on the <em>LocalLibrary</em> website. The very first thing we want to do is set up a MongoDB database that we can use to store our library data.</p> <p>For this tutorial, we're going to use the <a href="https://www.mongodb.com/products/platform/atlas-database" class="external" target="_blank">MongoDB Atlas</a> cloud-hosted sandbox database. This database tier is not considered suitable for production websites because it has no redundancy, but it is great for development and prototyping. We're using it here because it is free and easy to set up, and because MongoDB Atlas is a popular <em>database as a service</em> vendor that you might reasonably choose for your production database (other popular choices at the time of writing include <a href="https://scalegrid.io/" class="external" target="_blank">ScaleGrid</a> and <a href="https://www.objectrocket.com/" class="external" target="_blank">ObjectRocket</a>).</p> <div class="notecard note"> <p><strong>Note:</strong> If you prefer, you can set up a MongoDB database locally by downloading and installing the <a href="https://www.mongodb.com/try/download/community-edition/releases" class="external" target="_blank">appropriate binaries for your system</a>. The rest of the instructions in this article would be similar, except for the database URL you would specify when connecting. In the <a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/deployment">Express Tutorial Part 7: Deploying to Production</a> tutorial we host both the application and database on <a href="https://railway.app/" class="external" target="_blank">Railway</a>, but we could equally well have used a database on <a href="https://www.mongodb.com/products/platform/atlas-database" class="external" target="_blank">MongoDB Atlas</a>.</p> </div> <p>You will first need to <a href="https://www.mongodb.com/cloud/atlas/register" class="external" target="_blank">create an account</a> with MongoDB Atlas (this is free, and just requires that you enter basic contact details and acknowledge their terms of service).</p> <p>After logging in, you'll be taken to the <a href="https://cloud.mongodb.com/v2" class="external" target="_blank">home</a> screen:</p> <ol> <li> <p>Click the <strong>+ Create</strong> button in the <em>Overview</em> section.</p> <p><img src="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_createdatabase.jpg" alt="Create a database on MongoDB Atlas." width="1667" height="1174" loading="lazy"></p> </li> <li> <p>This will open the <em>Deploy your cluster</em> screen. Click on the <strong>M0 FREE</strong> option template.</p> <p><img src="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_deploy.jpg" alt="Choose a deployment option when using MongoDB Atlas." width="1828" height="879" loading="lazy"></p> </li> <li> <p>Scroll down the page to see the different options you can choose. <img src="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_createsharedcluster.jpg" alt="Choose a cloud provider when using MongoDB Atlas." width="1683" height="1235" loading="lazy"></p> <ul> <li>You can change the name of your Cluster under <em>Cluster Name</em>. We are keeping it as <code>Cluster0</code> for this tutorial.</li> <li>Deselect the <em>Preload sample dataset</em> checkbox, as we'll import our own sample data later on</li> <li>Select any provider and region from the <em>Provider</em> and <em>Region</em> sections. Different regions offer different providers.</li> <li>Tags are optional. We will not use them here.</li> <li>Click the <strong>Create deployment</strong> button (creation of the cluster will take some minutes).</li> </ul> </li> <li> <p>This will open the <em>Security Quickstart</em> section. <img src="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_securityquickstart.jpg" alt="Set up the Access Rules on the Security Quickstart screen on MongoDB Atlas." width="1939" height="2721" loading="lazy"></p> <ul> <li> <p>Enter a username and password for your application to use to access the database (above we have created a new login "cooluser"). Remember to copy and store the credentials safely as we will need them later on. Click the <strong>Create User</strong> button.</p> <div class="notecard note"> <p><strong>Note:</strong> Avoid using special characters in your MongoDB user password as mongoose may not parse the connection string properly.</p> </div> </li> <li> <p>Select <strong>Add by current IP address</strong> to allow access from your current computer</p> </li> <li> <p>Enter <code>0.0.0.0/0</code> in the IP Address field and then click the <strong>Add Entry</strong> button. This tells MongoDB that we want to allow access from anywhere.</p> <div class="notecard note"> <p><strong>Note:</strong> It is a best practice to limit the IP addresses that can connect to your database and other resources. Here we allow a connection from anywhere because we don't know where the request will come from after deployment.</p> </div> </li> <li> <p>Click the <strong>Finish and Close</strong> button.</p> </li> </ul> </li> <li> <p>This will open the following screen. Click on the <strong>Go to Overview</strong> button. <img src="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_accessrules.jpg" alt="Go to Databases after setting up Access Rules on MongoDB Atlas" width="1153" height="431" loading="lazy"></p> </li> <li> <p>You will return to the <em>Overview</em> screen. Click on the <em>Database</em> section under the <em>Deployment</em> menu on the left. Click the <strong>Browse Collections</strong> button. <img src="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_createcollection.jpg" alt="Setup a collection on MongoDB Atlas." width="2834" height="1316" loading="lazy"></p> </li> <li> <p>This will open the <em>Collections</em> section. Click the <strong>Add My Own Data</strong> button. <img src="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_adddata.jpg" alt="Create a database on MongoDB Atlas." width="1945" height="1334" loading="lazy"></p> </li> <li> <p>This will open the <em>Create Database</em> screen.</p> <p><img src="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_databasedetails.jpg" alt="Details during database creation on MongoDB Atlas." width="1206" height="808" loading="lazy"></p> <ul> <li>Enter the name for the new database as <code>local_library</code>.</li> <li>Enter the name of the collection as <code>Collection0</code>.</li> <li>Click the <strong>Create</strong> button to create the database.</li> </ul> </li> <li> <p>You will return to the <em>Collections</em> screen with your database created. <img src="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_databasecreated.jpg" alt="Database creation confirmation on MongoDB Atlas." width="1949" height="1329" loading="lazy"></p> <ul> <li>Click the <em>Overview</em> tab to return to the cluster overview.</li> </ul> </li> <li> <p>From the Cluster0 <em>Overview</em> screen click the <strong>Connect</strong> button.</p> <p><img src="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_connectbutton.jpg" alt="Configure connection after setting up a cluster in MongoDB Atlas." width="1949" height="900" loading="lazy"></p> </li> <li> <p>This will open the <em>Connect to Cluster0</em> screen.</p> <p><img src="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_connectforshortsrv.jpg" alt="Choose the Short SRV connection when setting up a connection on MongoDB Atlas." width="2373" height="1475" loading="lazy"></p> <ul> <li>Select your database user.</li> <li>Select the <em>Drivers</em> category, then the <em>Driver</em> <strong>Node.js</strong> and <em>Version</em> as shown.</li> <li><strong>DO NOT</strong> install the driver as suggested.</li> <li>Click the <strong>Copy</strong> icon to copy the connection string.</li> <li>Paste this in your local text editor.</li> <li>Replace <code>&lt;password&gt;</code> placeholder in the connection string with your user's password.</li> <li>Insert the database name "local_library" in the path before the options (<code>...mongodb.net/local_library?retryWrites...</code>)</li> <li>Save the file containing this string somewhere safe.</li> </ul> </li> </ol> <p>You have now created the database, and have a URL (with username and password) that can be used to access it. This will look something like: <code>mongodb+srv://your_user_name:your_password@cluster0.cojoign.mongodb.net/local_library?retryWrites=true&amp;w=majority&amp;appName=Cluster0</code></p></div></section><section aria-labelledby="install_mongoose"><h2 id="install_mongoose"><a href="#install_mongoose">Install Mongoose</a></h2><div class="section-content"><p>Open a command prompt and navigate to the directory where you created your <a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/skeleton_website">skeleton Local Library website</a>. Enter the following command to install Mongoose (and its dependencies) and add it to your <strong>package.json</strong> file, unless you have already done so when reading the <a href="#installing_mongoose_and_mongodb">Mongoose Primer</a> above.</p> <div class="code-example"><div class="example-header"><span class="language-name">bash</span></div><pre class="brush: bash notranslate"><code>npm install mongoose </code></pre></div></div></section><section aria-labelledby="connect_to_mongodb"><h2 id="connect_to_mongodb"><a href="#connect_to_mongodb">Connect to MongoDB</a></h2><div class="section-content"><p>Open <strong>/app.js</strong> (in the root of your project) and copy the following text below where you declare the <em>Express application object</em> (after the line <code>const app = express();</code>). Replace the database URL string ('<em>insert_your_database_url_here</em>') with the location URL representing your own database (i.e. using the information from <em>MongoDB Atlas</em>).</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>// Set up mongoose connection const mongoose = require("mongoose"); mongoose.set("strictQuery", false); const mongoDB = "insert_your_database_url_here"; main().catch((err) =&gt; console.log(err)); async function main() { await mongoose.connect(mongoDB); } </code></pre></div> <p>As discussed in the <a href="#connecting_to_mongodb">Mongoose primer</a> above, this code creates the default connection to the database and reports any errors to the console.</p> <p>Note that hard-coding database credentials in source code as shown above is not recommended. We do it here because it shows the core connection code, and because during development there is no significant risk that leaking these details will expose or corrupt sensitive information. We'll show you how to do this more safely when <a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/deployment#database_configuration">deploying to production</a>!</p></div></section><section aria-labelledby="defining_the_locallibrary_schema"><h2 id="defining_the_locallibrary_schema"><a href="#defining_the_locallibrary_schema">Defining the LocalLibrary Schema</a></h2><div class="section-content"><p>We will define a separate module for each model, as <a href="#one_schemamodel_per_file">discussed above</a>. Start by creating a folder for our models in the project root (<strong>/models</strong>) and then create separate files for each of the models:</p> <pre class="brush: plain notranslate">/express-locallibrary-tutorial // the project root /models author.js book.js bookinstance.js genre.js </pre></div></section><section aria-labelledby="author_model"><h3 id="author_model"><a href="#author_model">Author model</a></h3><div class="section-content"><p>Copy the <code>Author</code> schema code shown below and paste it into your <strong>./models/author.js</strong> file. The schema defines an author as having <code>String</code> SchemaTypes for the first and family names (required, with a maximum of 100 characters), and <code>Date</code> fields for the dates of birth and death.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>const mongoose = require("mongoose"); const Schema = mongoose.Schema; const AuthorSchema = new Schema({ first_name: { type: String, required: true, maxLength: 100 }, family_name: { type: String, required: true, maxLength: 100 }, date_of_birth: { type: Date }, date_of_death: { type: Date }, }); // Virtual for author's full name AuthorSchema.virtual("name").get(function () { // To avoid errors in cases where an author does not have either a family name or first name // We want to make sure we handle the exception by returning an empty string for that case let fullname = ""; if (this.first_name &amp;&amp; this.family_name) { fullname = `${this.family_name}, ${this.first_name}`; } return fullname; }); // Virtual for author's URL AuthorSchema.virtual("url").get(function () { // We don't use an arrow function as we'll need the this object return `/catalog/author/${this._id}`; }); // Export model module.exports = mongoose.model("Author", AuthorSchema); </code></pre></div> <p>We've also declared a <a href="#virtual_properties">virtual</a> for the AuthorSchema named "url" that returns the absolute URL required to get a particular instance of the model — we'll use the property in our templates whenever we need to get a link to a particular author.</p> <div class="notecard note"> <p><strong>Note:</strong> Declaring our URLs as a virtual in the schema is a good idea because then the URL for an item only ever needs to be changed in one place. At this point, a link using this URL wouldn't work, because we haven't got any routes handling code for individual model instances. We'll set those up in a later article!</p> </div> <p>At the end of the module, we export the model.</p></div></section><section aria-labelledby="book_model"><h3 id="book_model"><a href="#book_model">Book model</a></h3><div class="section-content"><p>Copy the <code>Book</code> schema code shown below and paste it into your <strong>./models/book.js</strong> file. Most of this is similar to the author model — we've declared a schema with a number of string fields and a virtual for getting the URL of specific book records, and we've exported the model.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>const mongoose = require("mongoose"); const Schema = mongoose.Schema; const BookSchema = new Schema({ title: { type: String, required: true }, author: { type: Schema.Types.ObjectId, ref: "Author", required: true }, summary: { type: String, required: true }, isbn: { type: String, required: true }, genre: [{ type: Schema.Types.ObjectId, ref: "Genre" }], }); // Virtual for book's URL BookSchema.virtual("url").get(function () { // We don't use an arrow function as we'll need the this object return `/catalog/book/${this._id}`; }); // Export model module.exports = mongoose.model("Book", BookSchema); </code></pre></div> <p>The main difference here is that we've created two references to other models:</p> <ul> <li>author is a reference to a single <code>Author</code> model object, and is required.</li> <li>genre is a reference to an array of <code>Genre</code> model objects. We haven't declared this object yet!</li> </ul></div></section><section aria-labelledby="bookinstance_model"><h3 id="bookinstance_model"><a href="#bookinstance_model">BookInstance model</a></h3><div class="section-content"><p>Finally, copy the <code>BookInstance</code> schema code shown below and paste it into your <strong>./models/bookinstance.js</strong> file. The <code>BookInstance</code> represents a specific copy of a book that someone might borrow and includes information about whether the copy is available, on what date it is expected back, and "imprint" (or version) details.</p> <div class="code-example"><div class="example-header"><span class="language-name">js</span></div><pre class="brush: js notranslate"><code>const mongoose = require("mongoose"); const Schema = mongoose.Schema; const BookInstanceSchema = new Schema({ book: { type: Schema.Types.ObjectId, ref: "Book", required: true }, // reference to the associated book imprint: { type: String, required: true }, status: { type: String, required: true, enum: ["Available", "Maintenance", "Loaned", "Reserved"], default: "Maintenance", }, due_back: { type: Date, default: Date.now }, }); // Virtual for bookinstance's URL BookInstanceSchema.virtual("url").get(function () { // We don't use an arrow function as we'll need the this object return `/catalog/bookinstance/${this._id}`; }); // Export model module.exports = mongoose.model("BookInstance", BookInstanceSchema); </code></pre></div> <p>The new things we show here are the field options:</p> <ul> <li><code>enum</code>: This allows us to set the allowed values of a string. In this case, we use it to specify the availability status of our books (using an enum means that we can prevent mis-spellings and arbitrary values for our status).</li> <li><code>default</code>: We use default to set the default status for newly created book instances to "Maintenance" and the default <code>due_back</code> date to <code>now</code> (note how you can call the Date function when setting the date!).</li> </ul> <p>Everything else should be familiar from our previous schema.</p></div></section><section aria-labelledby="genre_model_-_challenge"><h3 id="genre_model_-_challenge"><a href="#genre_model_-_challenge">Genre model - challenge</a></h3><div class="section-content"><p>Open your <strong>./models/genre.js</strong> file and create a schema for storing genres (the category of book, e.g. whether it is fiction or non-fiction, romance or military history, etc.).</p> <p>The definition will be very similar to the other models:</p> <ul> <li>The model should have a <code>String</code> SchemaType called <code>name</code> to describe the genre.</li> <li>This name should be required and have between 3 and 100 characters.</li> <li>Declare a <a href="#virtual_properties">virtual</a> for the genre's URL, named <code>url</code>.</li> <li>Export the model.</li> </ul></div></section><section aria-labelledby="testing_—_create_some_items"><h2 id="testing_—_create_some_items"><a href="#testing_—_create_some_items">Testing — create some items</a></h2><div class="section-content"><p>That's it. We now have all models for the site set up!</p> <p>In order to test the models (and to create some example books and other items that we can use in our next articles) we'll now run an <em>independent</em> script to create items of each type:</p> <ol> <li> <p>Download (or otherwise create) the file <a href="https://raw.githubusercontent.com/mdn/express-locallibrary-tutorial/main/populatedb.js" class="external" target="_blank">populatedb.js</a> inside your <em>express-locallibrary-tutorial</em> directory (in the same level as <code>package.json</code>).</p> <div class="notecard note"> <p><strong>Note:</strong> The code in <code>populatedb.js</code> may be useful in learning JavaScript, but understanding it is not necessary for this tutorial.</p> </div> </li> <li> <p>Run the script using node in your command prompt, passing in the URL of your <em>MongoDB</em> database (the same one you replaced the <em>insert_your_database_url_here</em> placeholder with, inside <code>app.js</code> earlier):</p> <div class="code-example"><div class="example-header"><span class="language-name">bash</span></div><pre class="brush: bash notranslate"><code>node populatedb &lt;your MongoDB url&gt; </code></pre></div> <div class="notecard note"> <p><strong>Note:</strong> On Windows you need to wrap the database URL inside double ("). On other operating systems you may need single (') quotation marks.</p> </div> </li> <li> <p>The script should run through to completion, displaying items as it creates them in the terminal.</p> </li> </ol> <div class="notecard note"> <p><strong>Note:</strong> Go to your database on MongoDB Atlas (in the <em>Collections</em> tab). You should now be able to drill down into individual collections of Books, Authors, Genres and BookInstances, and check out individual documents.</p> </div></div></section><section aria-labelledby="summary"><h2 id="summary"><a href="#summary">Summary</a></h2><div class="section-content"><p>In this article, we've learned a bit about databases and ORMs on Node/Express, and a lot about how Mongoose schema and models are defined. We then used this information to design and implement <code>Book</code>, <code>BookInstance</code>, <code>Author</code> and <code>Genre</code> models for the <em>LocalLibrary</em> website.</p> <p>Last of all, we tested our models by creating a number of instances (using a standalone script). In the next article we'll look at creating some pages to display these objects.</p></div></section><section aria-labelledby="see_also"><h2 id="see_also"><a href="#see_also">See also</a></h2><div class="section-content"><ul> <li><a href="https://expressjs.com/en/guide/database-integration.html" class="external" target="_blank">Database integration</a> (Express docs)</li> <li><a href="https://mongoosejs.com/" class="external" target="_blank">Mongoose website</a> (Mongoose docs)</li> <li><a href="https://mongoosejs.com/docs/guide.html" class="external" target="_blank">Mongoose Guide</a> (Mongoose docs)</li> <li><a href="https://mongoosejs.com/docs/validation.html" class="external" target="_blank">Validation</a> (Mongoose docs)</li> <li><a href="https://mongoosejs.com/docs/schematypes.html" class="external" target="_blank">Schema Types</a> (Mongoose docs)</li> <li><a href="https://mongoosejs.com/docs/models.html" class="external" target="_blank">Models</a> (Mongoose docs)</li> <li><a href="https://mongoosejs.com/docs/queries.html" class="external" target="_blank">Queries</a> (Mongoose docs)</li> <li><a href="https://mongoosejs.com/docs/populate.html" class="external" target="_blank">Population</a> (Mongoose docs)</li> </ul> <ul class="prev-next"><li><a class="button secondary" href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/skeleton_website"><span class="button-wrap"> Previous </span></a></li><li><a class="button secondary" href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs"><span class="button-wrap"> Overview: Express web framework (Node.js/JavaScript)</span></a></li><li><a class="button secondary" href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/routes"><span class="button-wrap"> Next </span></a></li></ul></div></section></article><aside class="article-footer"><div class="article-footer-inner"><div class="svg-container"><svg xmlns="http://www.w3.org/2000/svg" width="162" height="162" viewBox="0 0 162 162" fill="none" role="none"><mask id="b" fill="#fff"><path d="M97.203 47.04c8.113-7.886 18.004-13.871 28.906-17.492a78 78 0 0 1 33.969-3.39c11.443 1.39 22.401 5.295 32.024 11.411s17.656 14.28 23.476 23.86c5.819 9.579 9.269 20.318 10.083 31.385a69.85 69.85 0 0 1-5.387 32.44c-4.358 10.272-11.115 19.443-19.747 26.801-8.632 7.359-18.908 12.709-30.034 15.637l-6.17-21.698c7.666-2.017 14.746-5.703 20.694-10.773 5.948-5.071 10.603-11.389 13.606-18.467a48.14 48.14 0 0 0 3.712-22.352c-.561-7.625-2.938-15.025-6.948-21.625s-9.544-12.226-16.175-16.44-14.181-6.904-22.065-7.863a53.75 53.75 0 0 0-23.405 2.336c-7.513 2.495-14.327 6.62-19.918 12.053z"></path></mask><path stroke="url(#a)" stroke-dasharray="6, 6" stroke-width="2" d="M97.203 47.04c8.113-7.886 18.004-13.871 28.906-17.492a78 78 0 0 1 33.969-3.39c11.443 1.39 22.401 5.295 32.024 11.411s17.656 14.28 23.476 23.86c5.819 9.579 9.269 20.318 10.083 31.385a69.85 69.85 0 0 1-5.387 32.44c-4.358 10.272-11.115 19.443-19.747 26.801-8.632 7.359-18.908 12.709-30.034 15.637l-6.17-21.698c7.666-2.017 14.746-5.703 20.694-10.773 5.948-5.071 10.603-11.389 13.606-18.467a48.14 48.14 0 0 0 3.712-22.352c-.561-7.625-2.938-15.025-6.948-21.625s-9.544-12.226-16.175-16.44-14.181-6.904-22.065-7.863a53.75 53.75 0 0 0-23.405 2.336c-7.513 2.495-14.327 6.62-19.918 12.053z" mask="url(#b)" style="stroke:url(#a)" transform="translate(-63.992 -25.587)"></path><ellipse cx="8.066" cy="111.597" fill="var(--background-tertiary)" rx="53.677" ry="53.699" transform="matrix(.71707 -.697 .7243 .6895 0 0)"></ellipse><g clip-path="url(#c)" transform="translate(-63.992 -25.587)"><path fill="#9abff5" d="m144.256 137.379 32.906 12.434a4.41 4.41 0 0 1 2.559 5.667l-9.326 24.679a4.41 4.41 0 0 1-5.667 2.559l-8.226-3.108-2.332 6.17c-.466 1.233-.375 1.883-1.609 1.417l-2.253-.527c-.411-.155-.95-.594-1.206-1.161l-4.734-10.484-12.545-4.741a4.41 4.41 0 0 1-2.559-5.667l9.325-24.679a4.41 4.41 0 0 1 5.667-2.559m9.961 29.617 8.227 3.108 3.264-8.638-.498-6.768-4.113-1.555.548 7.258-4.319-1.632zm-12.339-4.663 8.226 3.108 3.264-8.637-.498-6.769-4.113-1.554.548 7.257-4.319-1.632z"></path></g><g clip-path="url(#d)" transform="translate(-63.992 -25.587)"><path fill="#81b0f3" d="M135.35 60.136 86.67 41.654c-3.346-1.27-7.124.428-8.394 3.775L64.414 81.938c-1.27 3.347.428 7.125 3.774 8.395l12.17 4.62-3.465 9.128c-.693 1.826-1.432 2.457.394 3.15l3.014 1.625c.609.231 1.637.274 2.477-.104l15.53-6.983 18.56 7.047c3.346 1.27 7.124-.428 8.395-3.775l13.862-36.51c1.27-3.346-.428-7.124-3.775-8.395M95.261 83.207l-12.17-4.62 4.852-12.779 7.19-7.017 6.085 2.31-7.725 7.51 6.389 2.426zm18.255 6.93-12.17-4.62 4.852-12.778 7.189-7.017 6.085 2.31-7.725 7.51 6.39 2.426z"></path></g><defs><clipPath id="c"><path fill="#fff" d="m198.638 146.586-65.056-24.583-24.583 65.057 65.056 24.582z"></path></clipPath><clipPath id="d"><path fill="#fff" d="m66.438 14.055 96.242 36.54-36.54 96.243-96.243-36.54z"></path></clipPath><linearGradient id="a" x1="97.203" x2="199.995" y1="47.04" y2="152.793" gradientUnits="userSpaceOnUse"><stop stop-color="#086DFC"></stop><stop offset="0.246" stop-color="#2C81FA"></stop><stop offset="0.516" stop-color="#5497F8"></stop><stop offset="0.821" stop-color="#80B0F6"></stop><stop offset="1" stop-color="#9ABFF5"></stop></linearGradient></defs></svg></div><h2>Help improve MDN</h2><fieldset class="feedback"><label>Was this page helpful to you?</label><div class="button-container"><button type="button" class="button primary has-icon yes"><span class="button-wrap"><span class="icon icon-thumbs-up "></span>Yes</span></button><button type="button" class="button primary has-icon no"><span class="button-wrap"><span class="icon icon-thumbs-down "></span>No</span></button></div></fieldset><a class="contribute" href="https://github.com/mdn/content/blob/main/CONTRIBUTING.md" title="This will take you to our contribution guidelines on GitHub." target="_blank" rel="noopener noreferrer">Learn how to contribute</a>.<p class="last-modified-date">This page was last modified on<!-- --> <time dateTime="2024-12-19T15:37:45.000Z">Dec 19, 2024</time> by<!-- --> <a href="/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/contributors.txt" rel="nofollow">MDN contributors</a>.</p><div id="on-github" class="on-github"><a href="https://github.com/mdn/content/blob/main/files/en-us/learn_web_development/extensions/server-side/express_nodejs/mongoose/index.md?plain=1" title="Folder: en-us/learn_web_development/extensions/server-side/express_nodejs/mongoose (Opens in a new tab)" target="_blank" rel="noopener noreferrer">View this page on GitHub</a> <!-- -->•<!-- --> <a href="https://github.com/mdn/content/issues/new?template=page-report.yml&amp;mdn-url=https%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FLearn_web_development%2FExtensions%2FServer-side%2FExpress_Nodejs%2Fmongoose&amp;metadata=%3C%21--+Do+not+make+changes+below+this+line+--%3E%0A%3Cdetails%3E%0A%3Csummary%3EPage+report+details%3C%2Fsummary%3E%0A%0A*+Folder%3A+%60en-us%2Flearn_web_development%2Fextensions%2Fserver-side%2Fexpress_nodejs%2Fmongoose%60%0A*+MDN+URL%3A+https%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FLearn_web_development%2FExtensions%2FServer-side%2FExpress_Nodejs%2Fmongoose%0A*+GitHub+URL%3A+https%3A%2F%2Fgithub.com%2Fmdn%2Fcontent%2Fblob%2Fmain%2Ffiles%2Fen-us%2Flearn_web_development%2Fextensions%2Fserver-side%2Fexpress_nodejs%2Fmongoose%2Findex.md%0A*+Last+commit%3A+https%3A%2F%2Fgithub.com%2Fmdn%2Fcontent%2Fcommit%2F5b20f5f4265f988f80f513db0e4b35c7e0cd70dc%0A*+Document+last+modified%3A+2024-12-19T15%3A37%3A45.000Z%0A%0A%3C%2Fdetails%3E" title="This will take you to GitHub to file a new issue." target="_blank" rel="noopener noreferrer">Report a problem with this content</a></div></div></aside></main></div></div><footer id="nav-footer" class="page-footer"><div class="page-footer-grid"><div class="page-footer-logo-col"><a href="/" class="mdn-footer-logo" aria-label="MDN homepage"><svg width="48" height="17" viewBox="0 0 48 17" fill="none" xmlns="http://www.w3.org/2000/svg"><title id="mdn-footer-logo-svg">MDN logo</title><path d="M20.04 16.512H15.504V10.416C15.504 9.488 15.344 8.824 15.024 8.424C14.72 8.024 14.264 7.824 13.656 7.824C12.92 7.824 12.384 8.064 12.048 8.544C11.728 9.024 11.568 9.64 11.568 10.392V14.184H13.008V16.512H8.472V10.416C8.472 9.488 8.312 8.824 7.992 8.424C7.688 8.024 7.232 7.824 6.624 7.824C5.872 7.824 5.336 8.064 5.016 8.544C4.696 9.024 4.536 9.64 4.536 10.392V14.184H6.6V16.512H0V14.184H1.44V8.04H0.024V5.688H4.536V7.32C5.224 6.088 6.32 5.472 7.824 5.472C8.608 5.472 9.328 5.664 9.984 6.048C10.64 6.432 11.096 7.016 11.352 7.8C11.992 6.248 13.168 5.472 14.88 5.472C15.856 5.472 16.72 5.776 17.472 6.384C18.224 6.992 18.6 7.936 18.6 9.216V14.184H20.04V16.512Z" fill="currentColor"></path><path d="M33.6714 16.512H29.1354V14.496C28.8314 15.12 28.3834 15.656 27.7914 16.104C27.1994 16.536 26.4154 16.752 25.4394 16.752C24.0154 16.752 22.8954 16.264 22.0794 15.288C21.2634 14.312 20.8554 12.984 20.8554 11.304C20.8554 9.688 21.2554 8.312 22.0554 7.176C22.8554 6.04 24.0634 5.472 25.6794 5.472C26.5594 5.472 27.2794 5.648 27.8394 6C28.3994 6.352 28.8314 6.8 29.1354 7.344V2.352H26.9754V0H32.2314V14.184H33.6714V16.512ZM29.1354 11.04V10.776C29.1354 9.88 28.8954 9.184 28.4154 8.688C27.9514 8.176 27.3674 7.92 26.6634 7.92C25.9754 7.92 25.3674 8.176 24.8394 8.688C24.3274 9.2 24.0714 10.008 24.0714 11.112C24.0714 12.152 24.3114 12.944 24.7914 13.488C25.2714 14.032 25.8394 14.304 26.4954 14.304C27.3114 14.304 27.9514 13.96 28.4154 13.272C28.8954 12.584 29.1354 11.84 29.1354 11.04Z" fill="currentColor"></path><path d="M47.9589 16.512H41.9829V14.184H43.4229V10.416C43.4229 9.488 43.2629 8.824 42.9429 8.424C42.6389 8.024 42.1829 7.824 41.5749 7.824C40.8389 7.824 40.2709 8.056 39.8709 8.52C39.4709 8.968 39.2629 9.56 39.2469 10.296V14.184H40.6869V16.512H34.7109V14.184H36.1509V8.04H34.5909V5.688H39.2469V7.344C39.9669 6.096 41.1269 5.472 42.7269 5.472C43.7509 5.472 44.6389 5.776 45.3909 6.384C46.1429 6.992 46.5189 7.936 46.5189 9.216V14.184H47.9589V16.512Z" fill="currentColor"></path></svg></a><p>Your blueprint for a better internet.</p><ul class="social-icons"><li><a href="https://mastodon.social/@mdn" target="_blank" rel="me noopener noreferrer"><span class="icon icon-mastodon"></span><span class="visually-hidden">MDN on Mastodon</span></a></li><li><a href="https://twitter.com/mozdevnet" target="_blank" rel="noopener noreferrer"><span class="icon icon-twitter-x"></span><span class="visually-hidden">MDN on X (formerly Twitter)</span></a></li><li><a href="https://github.com/mdn/" target="_blank" rel="noopener noreferrer"><span class="icon icon-github-mark-small"></span><span class="visually-hidden">MDN on GitHub</span></a></li><li><a href="/en-US/blog/rss.xml" target="_blank"><span class="icon icon-feed"></span><span class="visually-hidden">MDN Blog RSS Feed</span></a></li></ul></div><div class="page-footer-nav-col-1"><h2 class="footer-nav-heading">MDN</h2><ul class="footer-nav-list"><li class="footer-nav-item"><a href="/en-US/about">About</a></li><li class="footer-nav-item"><a href="/en-US/blog/">Blog</a></li><li class="footer-nav-item"><a href="https://www.mozilla.org/en-US/careers/listings/?team=ProdOps" target="_blank" rel="noopener noreferrer">Careers</a></li><li class="footer-nav-item"><a href="/en-US/advertising">Advertise with us</a></li></ul></div><div class="page-footer-nav-col-2"><h2 class="footer-nav-heading">Support</h2><ul class="footer-nav-list"><li class="footer-nav-item"><a class="footer-nav-link" href="https://support.mozilla.org/products/mdn-plus">Product help</a></li><li class="footer-nav-item"><a class="footer-nav-link" href="/en-US/docs/MDN/Community/Issues">Report an issue</a></li></ul></div><div class="page-footer-nav-col-3"><h2 class="footer-nav-heading">Our communities</h2><ul class="footer-nav-list"><li class="footer-nav-item"><a class="footer-nav-link" href="/en-US/community">MDN Community</a></li><li class="footer-nav-item"><a class="footer-nav-link" href="https://discourse.mozilla.org/c/mdn/236" target="_blank" rel="noopener noreferrer">MDN Forum</a></li><li class="footer-nav-item"><a class="footer-nav-link" href="/discord" target="_blank" rel="noopener noreferrer">MDN Chat</a></li></ul></div><div class="page-footer-nav-col-4"><h2 class="footer-nav-heading">Developers</h2><ul class="footer-nav-list"><li class="footer-nav-item"><a class="footer-nav-link" href="/en-US/docs/Web">Web Technologies</a></li><li class="footer-nav-item"><a class="footer-nav-link" href="/en-US/docs/Learn">Learn Web Development</a></li><li class="footer-nav-item"><a class="footer-nav-link" href="/en-US/plus">MDN Plus</a></li><li class="footer-nav-item"><a href="https://hacks.mozilla.org/" target="_blank" rel="noopener noreferrer">Hacks Blog</a></li></ul></div><div class="page-footer-moz"><a href="https://www.mozilla.org/" class="footer-moz-logo-link" target="_blank" rel="noopener noreferrer"><svg xmlns="http://www.w3.org/2000/svg" width="137" height="32" fill="none" viewBox="0 0 267.431 62.607"><path fill="#000" d="m13.913 23.056 5.33 25.356h2.195l5.33-25.356h14.267v38.976h-7.578V29.694h-2.194l-7.264 32.337h-7.343L9.418 29.694H7.223v32.337H-.354V23.056Zm47.137 9.123c9.12 0 14.423 5.385 14.423 15.214s-5.33 15.214-14.423 15.214c-9.12 0-14.423-5.385-14.423-15.214 0-9.855 5.304-15.214 14.423-15.214m0 24.363c4.285 0 6.428-2.196 6.428-7.032v-4.287c0-4.836-2.143-7.032-6.428-7.032s-6.428 2.196-6.428 7.032v4.287c0 4.836 2.143 7.032 6.428 7.032m18.473-.157 15.47-18.01h-15.26v-5.647h24.352v5.646L88.616 56.385h15.704v5.646H79.523Zm29.318-23.657h11.183V62.03h-7.578V38.375h-3.632v-5.646zm3.605-9.672h7.578v5.646h-7.578zm13.17 0h11.21v38.976h-7.578v-33.33h-3.632zm16.801 0H153.6v38.976h-7.577v-33.33h-3.632v-5.646zm29.03 9.123c4.442 0 7.394 2.143 8.231 5.881h2.194v-5.332h9.276v5.646h-3.632v18.011h3.632v5.646h-4.442c-3.135 0-4.834-1.699-4.834-4.836V56.7h-2.194c-.81 3.738-3.789 5.881-8.23 5.881-6.978 0-11.916-5.829-11.916-15.214 0-9.384 4.938-15.187 11.915-15.187m2.3 24.363c4.284 0 6.192-2.196 6.192-7.032v-4.287c0-4.836-1.908-7.032-6.193-7.032-4.18 0-6.193 2.196-6.193 7.032v4.287c0 4.836 2.012 7.032 6.193 7.032m48.34 5.489h-7.577V0h7.577zm6.585-29.643h32.165v-2.196l-21.295-7.634v-6.143l21.295-7.633V6.588h-25.345V0h32.165v12.522l-17.35 5.881V20.6l17.35 5.882v12.521h-38.985zm0-25.801h6.794v6.796h-6.794z"></path></svg></a><ul class="footer-moz-list"><li class="footer-moz-item"><a href="https://www.mozilla.org/privacy/websites/" class="footer-moz-link" target="_blank" rel="noopener noreferrer">Website Privacy Notice</a></li><li class="footer-moz-item"><a href="https://www.mozilla.org/privacy/websites/#cookies" class="footer-moz-link" target="_blank" rel="noopener noreferrer">Cookies</a></li><li class="footer-moz-item"><a href="https://www.mozilla.org/about/legal/terms/mozilla" class="footer-moz-link" target="_blank" rel="noopener noreferrer">Legal</a></li><li class="footer-moz-item"><a href="https://www.mozilla.org/about/governance/policies/participation/" class="footer-moz-link" target="_blank" rel="noopener noreferrer">Community Participation Guidelines</a></li></ul></div><div class="page-footer-legal"><p id="license" class="page-footer-legal-text">Visit<!-- --> <a href="https://www.mozilla.org" target="_blank" rel="noopener noreferrer">Mozilla Corporation’s</a> <!-- -->not-for-profit parent, the<!-- --> <a target="_blank" rel="noopener noreferrer" href="https://foundation.mozilla.org/">Mozilla Foundation</a>.<br/>Portions of this content are ©1998–<!-- -->2025<!-- --> by individual mozilla.org contributors. Content available under<!-- --> <a href="/en-US/docs/MDN/Writing_guidelines/Attrib_copyright_license">a Creative Commons license</a>.</p></div></div></footer></div><script type="application/json" id="hydration">{"url":"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose","doc":{"body":[{"type":"prose","value":{"id":null,"title":null,"isH3":false,"content":"<ul class=\"prev-next\"><li><a class=\"button secondary\" href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/skeleton_website\"><span class=\"button-wrap\"> Previous </span></a></li><li><a class=\"button secondary\" href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs\"><span class=\"button-wrap\"> Overview: Express web framework (Node.js/JavaScript)</span></a></li><li><a class=\"button secondary\" href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/routes\"><span class=\"button-wrap\"> Next </span></a></li></ul>\n<p>This article briefly introduces databases, and how to use them with Node/Express apps. It then goes on to show how we can use <a href=\"https://mongoosejs.com/\" class=\"external\" target=\"_blank\">Mongoose</a> to provide database access for the <a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Tutorial_local_library_website\">LocalLibrary</a> website. It explains how object schema and models are declared, the main field types, and basic validation. It also briefly shows a few of the main ways in which you can access model data.</p>\n<figure class=\"table-container\"><table>\n <tbody>\n <tr>\n <th scope=\"row\">Prerequisites:</th>\n <td>\n <a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/skeleton_website\">Express Tutorial Part 2: Creating a skeleton website</a>\n </td>\n </tr>\n <tr>\n <th scope=\"row\">Objective:</th>\n <td>To be able to design and create your own models using Mongoose.</td>\n </tr>\n </tbody>\n</table></figure>"}},{"type":"prose","value":{"id":"overview","title":"Overview","isH3":false,"content":"<p>Library staff will use the Local Library website to store information about books and borrowers, while library members will use it to browse and search for books, find out whether there are any copies available, and then reserve or borrow them. In order to store and retrieve information efficiently, we will store it in a <em>database</em>.</p>\n<p>Express apps can use many different databases, and there are several approaches you can use for performing <strong>C</strong>reate, <strong>R</strong>ead, <strong>U</strong>pdate and <strong>D</strong>elete (CRUD) operations. This tutorial provides a brief overview of some of the available options and then goes on to show in detail the particular mechanisms selected.</p>"}},{"type":"prose","value":{"id":"what_databases_can_i_use","title":"What databases can I use?","isH3":true,"content":"<p><em>Express</em> apps can use any database supported by <em>Node</em> (<em>Express</em> itself doesn't define any specific additional behavior/requirements for database management). There are <a href=\"https://expressjs.com/en/guide/database-integration.html\" class=\"external\" target=\"_blank\">many popular options</a>, including PostgreSQL, MySQL, Redis, SQLite, and MongoDB.</p>\n<p>When choosing a database, you should consider things like time-to-productivity/learning curve, performance, ease of replication/backup, cost, community support, etc. While there is no single \"best\" database, almost any of the popular solutions should be more than acceptable for a small-to-medium-sized site like our Local Library.</p>\n<p>For more information on the options see <a href=\"https://expressjs.com/en/guide/database-integration.html\" class=\"external\" target=\"_blank\">Database integration</a> (Express docs).</p>"}},{"type":"prose","value":{"id":"what_is_the_best_way_to_interact_with_a_database","title":"What is the best way to interact with a database?","isH3":true,"content":"<p>There are two common approaches for interacting with a database:</p>\n<ul>\n<li>Using the databases' native query language, such as SQL.</li>\n<li>Using an Object Relational Mapper (\"ORM\"). An ORM represents the website's data as JavaScript objects, which are then mapped to the underlying database. Some ORMs are tied to a specific database, while others provide a database-agnostic backend.</li>\n</ul>\n<p>The very best <em>performance</em> can be gained by using SQL, or whatever query language is supported by the database. ODM's are often slower because they use translation code to map between objects and the database format, which may not use the most efficient database queries (this is particularly true if the ODM supports different database backends, and must make greater compromises in terms of what database features are supported).</p>\n<p>The benefit of using an ORM is that programmers can continue to think in terms of JavaScript objects rather than database semantics — this is particularly true if you need to work with different databases (on either the same or different websites). They also provide an obvious place to perform data validation.</p>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nUsing ODM/ORMs often results in lower costs for development and maintenance! Unless you're very familiar with the native query language or performance is paramount, you should strongly consider using an ODM.</p>\n</div>"}},{"type":"prose","value":{"id":"what_ormodm_should_i_use","title":"What ORM/ODM should I use?","isH3":true,"content":"<p>There are many ODM/ORM solutions available on the npm package manager site (check out the <a href=\"https://www.npmjs.com/search?q=keywords:odm\" class=\"external\" target=\"_blank\">odm</a> and <a href=\"https://www.npmjs.com/search?q=keywords:orm\" class=\"external\" target=\"_blank\">orm</a> tags for a subset!).</p>\n<p>A few solutions that were popular at the time of writing are:</p>\n<ul>\n<li><a href=\"https://www.npmjs.com/package/mongoose\" class=\"external\" target=\"_blank\">Mongoose</a>: Mongoose is a <a href=\"https://www.mongodb.com/\" class=\"external\" target=\"_blank\">MongoDB</a> object modeling tool designed to work in an asynchronous environment.</li>\n<li><a href=\"https://www.npmjs.com/package/waterline\" class=\"external\" target=\"_blank\">Waterline</a>: An ORM extracted from the Express-based <a href=\"https://sailsjs.com/\" class=\"external\" target=\"_blank\">Sails</a> web framework. It provides a uniform API for accessing numerous different databases, including Redis, MySQL, LDAP, MongoDB, and Postgres.</li>\n<li><a href=\"https://www.npmjs.com/package/bookshelf\" class=\"external\" target=\"_blank\">Bookshelf</a>: Features both promise-based and traditional callback interfaces, providing transaction support, eager/nested-eager relation loading, polymorphic associations, and support for one-to-one, one-to-many, and many-to-many relations. Works with PostgreSQL, MySQL, and SQLite3.</li>\n<li><a href=\"https://www.npmjs.com/package/objection\" class=\"external\" target=\"_blank\">Objection</a>: Makes it as easy as possible to use the full power of SQL and the underlying database engine (supports SQLite3, Postgres, and MySQL).</li>\n<li><a href=\"https://www.npmjs.com/package/sequelize\" class=\"external\" target=\"_blank\">Sequelize</a> is a promise-based ORM for Node.js and io.js. It supports the dialects PostgreSQL, MySQL, MariaDB, SQLite, and MSSQL and features solid transaction support, relations, read replication and more.</li>\n<li><a href=\"https://node-orm.readthedocs.io/en/latest/\" class=\"external\" target=\"_blank\">Node ORM2</a> is an Object Relationship Manager for NodeJS. It supports MySQL, SQLite, and Postgres, helping to work with the database using an object-oriented approach.</li>\n<li><a href=\"https://graphql.org/\" class=\"external\" target=\"_blank\">GraphQL</a>: Primarily a query language for restful APIs, GraphQL is very popular, and has features available for reading data from databases.</li>\n</ul>\n<p>As a general rule, you should consider both the features provided and the \"community activity\" (downloads, contributions, bug reports, quality of documentation, etc.) when selecting a solution. At the time of writing Mongoose is by far the most popular ODM, and is a reasonable choice if you're using MongoDB for your database.</p>"}},{"type":"prose","value":{"id":"using_mongoose_and_mongodb_for_the_locallibrary","title":"Using Mongoose and MongoDB for the LocalLibrary","isH3":true,"content":"<p>For the <em>Local Library</em> example (and the rest of this topic) we're going to use the <a href=\"https://www.npmjs.com/package/mongoose\" class=\"external\" target=\"_blank\">Mongoose ODM</a> to access our library data. Mongoose acts as a front end to <a href=\"https://www.mongodb.com/company/what-is-mongodb\" class=\"external\" target=\"_blank\">MongoDB</a>, an open source <a href=\"https://en.wikipedia.org/wiki/NoSQL\" class=\"external\" target=\"_blank\">NoSQL</a> database that uses a document-oriented data model. A \"collection\" of \"documents\" in a MongoDB database <a href=\"https://www.mongodb.com/docs/manual/core/databases-and-collections/\" class=\"external\" target=\"_blank\">is analogous to</a> a \"table\" of \"rows\" in a relational database.</p>\n<p>This ODM and database combination is extremely popular in the Node community, partially because the document storage and query system looks very much like JSON, and is hence familiar to JavaScript developers.</p>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nYou don't need to know MongoDB in order to use Mongoose, although parts of the <a href=\"https://mongoosejs.com/docs/guide.html\" class=\"external\" target=\"_blank\">Mongoose documentation</a> <em>are</em> easier to use and understand if you are already familiar with MongoDB.</p>\n</div>\n<p>The rest of this tutorial shows how to define and access the Mongoose schema and models for the <a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Tutorial_local_library_website\">LocalLibrary website</a> example.</p>"}},{"type":"prose","value":{"id":"designing_the_locallibrary_models","title":"Designing the LocalLibrary models","isH3":false,"content":"<p>Before you jump in and start coding the models, it's worth taking a few minutes to think about what data we need to store and the relationships between the different objects.</p>\n<p>We know that we need to store information about books (title, summary, author, genre, ISBN) and that we might have multiple copies available (with globally unique ids, availability statuses, etc.). We might need to store more information about the author than just their name, and there might be multiple authors with the same or similar names. We want to be able to sort information based on the book title, author, genre, and category.</p>\n<p>When designing your models it makes sense to have separate models for every \"object\" (a group of related information). In this case some obvious candidates for these models are books, book instances, and authors.</p>\n<p>You might also want to use models to represent selection-list options (e.g. like a drop-down list of choices), rather than hard-coding the choices into the website itself — this is recommended when all the options aren't known up front or may change. A good example is a genre (e.g. fantasy, science fiction, etc.).</p>\n<p>Once we've decided on our models and fields, we need to think about the relationships between them.</p>\n<p>With that in mind, the UML association diagram below shows the models we'll define in this case (as boxes). As discussed above, we've created models for the book (the generic details of the book), book instance (status of specific physical copies of the book available in the system), and author. We have also decided to have a model for the genre so that values can be created dynamically. We've decided not to have a model for the <code>BookInstance:status</code> — we will hard code the acceptable values because we don't expect these to change. Within each of the boxes, you can see the model name, the field names and types, and also the methods and their return types.</p>\n<p>The diagram also shows the relationships between the models, including their <em>multiplicities</em>. The multiplicities are the numbers on the diagram showing the numbers (maximum and minimum) of each model that may be present in the relationship. For example, the connecting line between the boxes shows that <code>Book</code> and a <code>Genre</code> are related. The numbers close to the <code>Book</code> model show that a <code>Genre</code> must have zero or more <code>Book</code>s (as many as you like), while the numbers on the other end of the line next to the <code>Genre</code> show that a book can have zero or more associated <code>Genre</code>s.</p>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nAs discussed in our <a href=\"#mongoose_primer\">Mongoose primer</a> below it is often better to have the field that defines the relationship between the documents/models in just <em>one</em> model (you can still find the reverse relationship by searching for the associated <code>_id</code> in the other model). Below we have chosen to define the relationship between <code>Book</code>/<code>Genre</code> and <code>Book</code>/<code>Author</code> in the Book schema, and the relationship between the <code>Book</code>/<code>BookInstance</code> in the <code>BookInstance</code> Schema. This choice was somewhat arbitrary — we could equally well have had the field in the other schema.</p>\n</div>\n<p><img src=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/library_website_-_mongoose_express.png\" alt=\"Mongoose Library Model with correct cardinality\" width=\"737\" height=\"620\" loading=\"lazy\"></p>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nThe next section provides a basic primer explaining how models are defined and used. As you read it, consider how we will construct each of the models in the diagram above.</p>\n</div>"}},{"type":"prose","value":{"id":"database_apis_are_asynchronous","title":"Database APIs are asynchronous","isH3":true,"content":"<p>Database methods to create, find, update, or delete records are asynchronous.\nWhat this means is that the methods return immediately, and the code to handle the success or failure of the method runs at a later time when the operation completes.\nOther code can execute while the server is waiting for the database operation to complete, so the server can remain responsive to other requests.</p>\n<p>JavaScript has a number of mechanisms for supporting asynchronous behavior.\nHistorically JavaScript relied heavily on passing <a href=\"/en-US/docs/Learn_web_development/Extensions/Async_JS/Introducing\">callback functions</a> to asynchronous methods to handle the success and error cases.\nIn modern JavaScript callbacks have largely been replaced by <a href=\"/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise\">Promises</a>.\nPromises are objects that are (immediately) returned by an asynchronous method that represent its future state.\nWhen the operation completes, the promise object is \"settled\", and resolves an object that represents the result of the operation or an error.</p>\n<p>There are two main ways you can use promises to run code when a promise is settled, and we highly recommend that you read <a href=\"/en-US/docs/Learn_web_development/Extensions/Async_JS/Promises\">How to use promises</a> for a high level overview of both approaches.\nIn this tutorial, we'll primarily be using <a href=\"/en-US/docs/Web/JavaScript/Reference/Operators/await\"><code>await</code></a> to wait on promise completion within an <a href=\"/en-US/docs/Web/JavaScript/Reference/Statements/async_function\"><code>async function</code></a>, because this leads to more readable and understandable asynchronous code.</p>\n<p>The way this approach works is that you use the <code>async function</code> keyword to mark a function as asynchronous, and then inside that function apply <code>await</code> to any method that returns a promise.\nWhen the asynchronous function is executed its operation is paused at the first <code>await</code> method until the promise settles.\nFrom the perspective of the surrounding code the asynchronous function then returns and the code after it is able to run.\nLater when the promise settles, the <code>await</code> method inside the asynchronous function returns with the result, or an error is thrown if the promise was rejected.\nThe code in the asynchronous function then executes until either another <code>await</code> is encountered, at which point it will pause again, or until all the code in the function has been run.</p>\n<p>You can see how this works in the example below.\n<code>myFunction()</code> is an asynchronous function that is called within a <a href=\"/en-US/docs/Web/JavaScript/Reference/Statements/try...catch\"><code>try...catch</code></a> block.\nWhen <code>myFunction()</code> is run, code execution is paused at <code>methodThatReturnsPromise()</code> until the promise resolves, at which point the code continues to <code>aFunctionThatReturnsPromise()</code> and waits again.\nThe code in the <code>catch</code> block runs if an error is thrown in the asynchronous function, and this will happen if the promise returned by either of the methods is rejected.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>async function myFunction {\n // ...\n await someObject.methodThatReturnsPromise();\n // ...\n await aFunctionThatReturnsPromise();\n // ...\n}\n\ntry {\n // ...\n myFunction();\n // ...\n} catch (e) {\n // error handling code\n}\n</code></pre></div>\n<p>The asynchronous methods above are run in sequence.\nIf the methods don't depend on each other then you can run them in parallel and finish the whole operation more quickly.\nThis is done using the <a href=\"/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all\"><code>Promise.all()</code></a> method, which takes an iterable of promises as input and returns a single <code>Promise</code>.\nThis returned promise fulfills when all of the input's promises fulfill, with an array of the fulfillment values.\nIt rejects when any of the input's promises rejects, with this first rejection reason.</p>\n<p>The code below shows how this works.\nFirst, we have two functions that return promises.\nWe <code>await</code> on both of them to complete using the promise returned by <code>Promise.all()</code>.\nOnce they both complete <code>await</code> returns and the results array is populated,\nthe function then continues to the next <code>await</code>, and waits until the promise returned by <code>anotherFunctionThatReturnsPromise()</code> is settled.\nYou would call the <code>myFunction()</code> in a <code>try...catch</code> block to catch any errors.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>async function myFunction {\n // ...\n const [resultFunction1, resultFunction2] = await Promise.all([\n functionThatReturnsPromise1(),\n functionThatReturnsPromise2()\n ]);\n // ...\n await anotherFunctionThatReturnsPromise(resultFunction1);\n}\n</code></pre></div>\n<p>Promises with <code>await</code>/<code>async</code> allow both flexible and \"comprehensible\" control over asynchronous execution!</p>"}},{"type":"prose","value":{"id":"mongoose_primer","title":"Mongoose primer","isH3":false,"content":"<p>This section provides an overview of how to connect Mongoose to a MongoDB database, how to define a schema and a model, and how to make basic queries.</p>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nThis primer is heavily influenced by the <a href=\"https://www.npmjs.com/package/mongoose\" class=\"external\" target=\"_blank\">Mongoose quick start</a> on <em>npm</em> and the <a href=\"https://mongoosejs.com/docs/guide.html\" class=\"external\" target=\"_blank\">official documentation</a>.</p>\n</div>"}},{"type":"prose","value":{"id":"installing_mongoose_and_mongodb","title":"Installing Mongoose and MongoDB","isH3":true,"content":"<p>Mongoose is installed in your project (<strong>package.json</strong>) like any other dependency — using npm.\nTo install it, use the following command inside your project folder:</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">bash</span></div><pre class=\"brush: bash notranslate\"><code>npm install mongoose\n</code></pre></div>\n<p>Installing <em>Mongoose</em> adds all its dependencies, including the MongoDB database driver, but it does not install MongoDB itself. If you want to install a MongoDB server then you can <a href=\"https://www.mongodb.com/try/download/community\" class=\"external\" target=\"_blank\">download installers from here</a> for various operating systems and install it locally. You can also use cloud-based MongoDB instances.</p>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nFor this tutorial, we'll be using the <a href=\"https://www.mongodb.com/\" class=\"external\" target=\"_blank\">MongoDB Atlas</a> cloud-based <em>database as a service</em> free tier to provide the database. This is suitable for development and makes sense for the tutorial because it makes \"installation\" operating system independent (database-as-a-service is also one approach you might use for your production database).</p>\n</div>"}},{"type":"prose","value":{"id":"connecting_to_mongodb","title":"Connecting to MongoDB","isH3":true,"content":"<p><em>Mongoose</em> requires a connection to a MongoDB database.\nYou can <code>require()</code> and connect to a locally hosted database with <code>mongoose.connect()</code> as shown below (for the tutorial we'll instead connect to an internet-hosted database).</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>// Import the mongoose module\nconst mongoose = require(\"mongoose\");\n\n// Set `strictQuery: false` to globally opt into filtering by properties that aren't in the schema\n// Included because it removes preparatory warnings for Mongoose 7.\n// See: https://mongoosejs.com/docs/migrating_to_6.html#strictquery-is-removed-and-replaced-by-strict\nmongoose.set(\"strictQuery\", false);\n\n// Define the database URL to connect to.\nconst mongoDB = \"mongodb://127.0.0.1/my_database\";\n\n// Wait for database to connect, logging an error if there is a problem\nmain().catch((err) =&gt; console.log(err));\nasync function main() {\n await mongoose.connect(mongoDB);\n}\n</code></pre></div>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nAs discussed in the <a href=\"#database_apis_are_asynchronous\">Database APIs are asynchronous</a> section, here we <code>await</code> on the promise returned by the <code>connect()</code> method within an <code>async</code> function.\nWe use the promise <code>catch()</code> handler to handle any errors when trying to connect, but we might also have called <code>main()</code> within a <code>try...catch</code> block.</p>\n</div>\n<p>You can get the default <code>Connection</code> object with <code>mongoose.connection</code>.\nIf you need to create additional connections you can use <code>mongoose.createConnection()</code>.\nThis takes the same form of database URI (with host, database, port, options, etc.) as <code>connect()</code> and returns a <code>Connection</code> object).\nNote that <code>createConnection()</code> returns immediately; if you need to wait on the connection to be established you can call it with <code>asPromise()</code> to return a promise (<code>mongoose.createConnection(mongoDB).asPromise()</code>).</p>"}},{"type":"prose","value":{"id":"defining_and_creating_models","title":"Defining and creating models","isH3":true,"content":"<p>Models are <em>defined</em> using the <code>Schema</code> interface. The Schema allows you to define the fields stored in each document along with their validation requirements and default values. In addition, you can define static and instance helper methods to make it easier to work with your data types, and also virtual properties that you can use like any other field, but which aren't actually stored in the database (we'll discuss a bit further below).</p>\n<p>Schemas are then \"compiled\" into models using the <code>mongoose.model()</code> method. Once you have a model you can use it to find, create, update, and delete objects of the given type.</p>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nEach model maps to a <em>collection</em> of <em>documents</em> in the MongoDB database. The documents will contain the fields/schema types defined in the model <code>Schema</code>.</p>\n</div>\n<h4 id=\"defining_schemas\">Defining schemas</h4>\n<p>The code fragment below shows how you might define a simple schema. First you <code>require()</code> mongoose, then use the Schema constructor to create a new schema instance, defining the various fields inside it in the constructor's object parameter.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>// Require Mongoose\nconst mongoose = require(\"mongoose\");\n\n// Define a schema\nconst Schema = mongoose.Schema;\n\nconst SomeModelSchema = new Schema({\n a_string: String,\n a_date: Date,\n});\n</code></pre></div>\n<p>In the case above we just have two fields, a string and a date. In the next sections, we will show some of the other field types, validation, and other methods.</p>\n<h4 id=\"creating_a_model\">Creating a model</h4>\n<p>Models are created from schemas using the <code>mongoose.model()</code> method:</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>// Define schema\nconst Schema = mongoose.Schema;\n\nconst SomeModelSchema = new Schema({\n a_string: String,\n a_date: Date,\n});\n\n// Compile model from schema\nconst SomeModel = mongoose.model(\"SomeModel\", SomeModelSchema);\n</code></pre></div>\n<p>The first argument is the singular name of the collection that will be created for your model (Mongoose will create the database collection for the model <em>SomeModel</em> above), and the second argument is the schema you want to use in creating the model.</p>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nOnce you've defined your model classes you can use them to create, update, or delete records, and run queries to get all records or particular subsets of records. We'll show you how to do this in the <a href=\"#using_models\">Using models</a> section, and when we create our views.</p>\n</div>\n<h4 id=\"schema_types_fields\">Schema types (fields)</h4>\n<p>A schema can have an arbitrary number of fields — each one represents a field in the documents stored in <em>MongoDB</em>.\nAn example schema showing many of the common field types and how they are declared is shown below.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>const schema = new Schema({\n name: String,\n binary: Buffer,\n living: Boolean,\n updated: { type: Date, default: Date.now() },\n age: { type: Number, min: 18, max: 65, required: true },\n mixed: Schema.Types.Mixed,\n _someId: Schema.Types.ObjectId,\n array: [],\n ofString: [String], // You can also have an array of each of the other types too.\n nested: { stuff: { type: String, lowercase: true, trim: true } },\n});\n</code></pre></div>\n<p>Most of the <a href=\"https://mongoosejs.com/docs/schematypes.html\" class=\"external\" target=\"_blank\">SchemaTypes</a> (the descriptors after \"type:\" or after field names) are self-explanatory. The exceptions are:</p>\n<ul>\n<li><code>ObjectId</code>: Represents specific instances of a model in the database. For example, a book might use this to represent its author object. This will actually contain the unique ID (<code>_id</code>) for the specified object. We can use the <code>populate()</code> method to pull in the associated information when needed.</li>\n<li><a href=\"https://mongoosejs.com/docs/schematypes.html#mixed\" class=\"external\" target=\"_blank\"><code>Mixed</code></a>: An arbitrary schema type.</li>\n<li><code>[]</code>: An array of items. You can perform JavaScript array operations on these models (push, pop, unshift, etc.). The examples above show an array of objects without a specified type and an array of <code>String</code> objects, but you can have an array of any type of object.</li>\n</ul>\n<p>The code also shows both ways of declaring a field:</p>\n<ul>\n<li>\n<p>Field <em>name</em> and <em>type</em> as a key-value pair (i.e. as done with fields <code>name</code>, <code>binary</code> and <code>living</code>).</p>\n</li>\n<li>\n<p>Field <em>name</em> followed by an object defining the <code>type</code>, and any other <em>options</em> for the field. Options include things like:</p>\n<ul>\n<li>default values.</li>\n<li>built-in validators (e.g. max/min values) and custom validation functions.</li>\n<li>Whether the field is required</li>\n<li>Whether <code>String</code> fields should automatically be set to lowercase, uppercase, or trimmed (e.g. <code>{ type: String, lowercase: true, trim: true }</code>)</li>\n</ul>\n</li>\n</ul>\n<p>For more information about options see <a href=\"https://mongoosejs.com/docs/schematypes.html\" class=\"external\" target=\"_blank\">SchemaTypes</a> (Mongoose docs).</p>\n<h4 id=\"validation\">Validation</h4>\n<p>Mongoose provides built-in and custom validators, and synchronous and asynchronous validators. It allows you to specify both the acceptable range of values and the error message for validation failure in all cases.</p>\n<p>The built-in validators include:</p>\n<ul>\n<li>\n<p>All <a href=\"https://mongoosejs.com/docs/schematypes.html\" class=\"external\" target=\"_blank\">SchemaTypes</a> have the built-in <a href=\"https://mongoosejs.com/docs/api.html#schematype_SchemaType-required\" class=\"external\" target=\"_blank\">required</a> validator. This is used to specify whether the field must be supplied in order to save a document.</p>\n</li>\n<li>\n<p><a href=\"https://mongoosejs.com/docs/api/schemanumber.html\" class=\"external\" target=\"_blank\">Numbers</a> have <a href=\"https://mongoosejs.com/docs/api/schemanumber.html#SchemaNumber.prototype.min()\" class=\"external\" target=\"_blank\">min</a> and <a href=\"https://mongoosejs.com/docs/api/schemanumber.html#SchemaNumber.prototype.max()\" class=\"external\" target=\"_blank\">max</a> validators.</p>\n</li>\n<li>\n<p><a href=\"https://mongoosejs.com/docs/api/schemastring.html\" class=\"external\" target=\"_blank\">Strings</a> have:</p>\n<ul>\n<li><a href=\"https://mongoosejs.com/docs/api/schemastring.html#SchemaString.prototype.enum()\" class=\"external\" target=\"_blank\">enum</a>: specifies the set of allowed values for the field.</li>\n<li><a href=\"https://mongoosejs.com/docs/api/schemastring.html#SchemaString.prototype.match()\" class=\"external\" target=\"_blank\">match</a>: specifies a regular expression that the string must match.</li>\n<li><a href=\"https://mongoosejs.com/docs/api/schemastring.html#SchemaString.prototype.maxlength()\" class=\"external\" target=\"_blank\">maxLength</a> and <a href=\"https://mongoosejs.com/docs/api/schemastring.html#SchemaString.prototype.minlength()\" class=\"external\" target=\"_blank\">minLength</a> for the string.</li>\n</ul>\n</li>\n</ul>\n<p>The example below (slightly modified from the Mongoose documents) shows how you can specify some of the validator types and error messages:</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>const breakfastSchema = new Schema({\n eggs: {\n type: Number,\n min: [6, \"Too few eggs\"],\n max: 12,\n required: [true, \"Why no eggs?\"],\n },\n drink: {\n type: String,\n enum: [\"Coffee\", \"Tea\", \"Water\"],\n },\n});\n</code></pre></div>\n<p>For complete information on field validation see <a href=\"https://mongoosejs.com/docs/validation.html\" class=\"external\" target=\"_blank\">Validation</a> (Mongoose docs).</p>\n<h4 id=\"virtual_properties\">Virtual properties</h4>\n<p>Virtual properties are document properties that you can get and set but that do not get persisted to MongoDB. The getters are useful for formatting or combining fields, while setters are useful for de-composing a single value into multiple values for storage. The example in the documentation constructs (and deconstructs) a full name virtual property from a first and last name field, which is easier and cleaner than constructing a full name every time one is used in a template.</p>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nWe will use a virtual property in the library to define a unique URL for each model record using a path and the record's <code>_id</code> value.</p>\n</div>\n<p>For more information see <a href=\"https://mongoosejs.com/docs/guide.html#virtuals\" class=\"external\" target=\"_blank\">Virtuals</a> (Mongoose documentation).</p>\n<h4 id=\"methods_and_query_helpers\">Methods and query helpers</h4>\n<p>A schema can also have <a href=\"https://mongoosejs.com/docs/guide.html#methods\" class=\"external\" target=\"_blank\">instance methods</a>, <a href=\"https://mongoosejs.com/docs/guide.html#statics\" class=\"external\" target=\"_blank\">static methods</a>, and <a href=\"https://mongoosejs.com/docs/guide.html#query-helpers\" class=\"external\" target=\"_blank\">query helpers</a>. The instance and static methods are similar, but with the obvious difference that an instance method is associated with a particular record and has access to the current object. Query helpers allow you to extend mongoose's <a href=\"https://mongoosejs.com/docs/queries.html\" class=\"external\" target=\"_blank\">chainable query builder API</a> (for example, allowing you to add a query \"byName\" in addition to the <code>find()</code>, <code>findOne()</code> and <code>findById()</code> methods).</p>"}},{"type":"prose","value":{"id":"using_models","title":"Using models","isH3":true,"content":"<p>Once you've created a schema you can use it to create models. The model represents a collection of documents in the database that you can search, while the model's instances represent individual documents that you can save and retrieve.</p>\n<p>We provide a brief overview below. For more information see: <a href=\"https://mongoosejs.com/docs/models.html\" class=\"external\" target=\"_blank\">Models</a> (Mongoose docs).</p>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nCreation, update, deletion and querying of records are asynchronous operations that return a <a href=\"/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise\">promise</a>.\nThe examples below show just the use of the relevant methods and <code>await</code> (i.e. the essential code for using the methods).\nThe surrounding <code>async function</code> and <code>try...catch</code> block to catch errors are omitted for clarity.\nFor more information on using <code>await/async</code> see <a href=\"#database_apis_are_asynchronous\">Database APIs are asynchronous</a> above.</p>\n</div>\n<h4 id=\"creating_and_modifying_documents\">Creating and modifying documents</h4>\n<p>To create a record you can define an instance of the model and then call <a href=\"https://mongoosejs.com/docs/api/model.html#Model.prototype.save\" class=\"external\" target=\"_blank\"><code>save()</code></a> on it.\nThe examples below assume <code>SomeModel</code> is a model (with a single field <code>name</code>) that we have created from our schema.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>// Create an instance of model SomeModel\nconst awesome_instance = new SomeModel({ name: \"awesome\" });\n\n// Save the new model instance asynchronously\nawait awesome_instance.save();\n</code></pre></div>\n<p>You can also use <a href=\"https://mongoosejs.com/docs/api/model.html#Model.create\" class=\"external\" target=\"_blank\"><code>create()</code></a> to define the model instance at the same time as you save it.\nBelow we create just one, but you can create multiple instances by passing in an array of objects.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>await SomeModel.create({ name: \"also_awesome\" });\n</code></pre></div>\n<p>Every model has an associated connection (this will be the default connection when you use <code>mongoose.model()</code>). You create a new connection and call <code>.model()</code> on it to create the documents on a different database.</p>\n<p>You can access the fields in this new record using the dot syntax, and change the values. You have to call <code>save()</code> or <code>update()</code> to store modified values back to the database.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>// Access model field values using dot notation\nconsole.log(awesome_instance.name); //should log 'also_awesome'\n\n// Change record by modifying the fields, then calling save().\nawesome_instance.name = \"New cool name\";\nawait awesome_instance.save();\n</code></pre></div>\n<h4 id=\"searching_for_records\">Searching for records</h4>\n<p>You can search for records using query methods, specifying the query conditions as a JSON document. The code fragment below shows how you might find all athletes in a database that play tennis, returning just the fields for athlete <em>name</em> and <em>age</em>. Here we just specify one matching field (sport) but you can add more criteria, specify regular expression criteria, or remove the conditions altogether to return all athletes.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>const Athlete = mongoose.model(\"Athlete\", yourSchema);\n\n// find all athletes who play tennis, returning the 'name' and 'age' fields\nconst tennisPlayers = await Athlete.find(\n { sport: \"Tennis\" },\n \"name age\",\n).exec();\n</code></pre></div>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nIt is important to remember that not finding any results is <strong>not an error</strong> for a search — but it may be a fail-case in the context of your application.\nIf your application expects a search to find a value you can check the number of entries returned in the result.</p>\n</div>\n<p>Query APIs, such as <a href=\"https://mongoosejs.com/docs/api/model.html#Model.find()\" class=\"external\" target=\"_blank\"><code>find()</code></a>, return a variable of type <a href=\"https://mongoosejs.com/docs/api/query.html\" class=\"external\" target=\"_blank\">Query</a>.\nYou can use a query object to build up a query in parts before executing it with the <a href=\"https://mongoosejs.com/docs/api/query.html#Query.prototype.exec\" class=\"external\" target=\"_blank\"><code>exec()</code></a> method.\n<code>exec()</code> executes the query and returns a promise that you can <code>await</code> on for the result.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>// find all athletes that play tennis\nconst query = Athlete.find({ sport: \"Tennis\" });\n\n// selecting the 'name' and 'age' fields\nquery.select(\"name age\");\n\n// limit our results to 5 items\nquery.limit(5);\n\n// sort by age\nquery.sort({ age: -1 });\n\n// execute the query at a later time\nquery.exec();\n</code></pre></div>\n<p>Above we've defined the query conditions in the <a href=\"https://mongoosejs.com/docs/api/model.html#Model.find()\" class=\"external\" target=\"_blank\"><code>find()</code></a> method. We can also do this using a <a href=\"https://mongoosejs.com/docs/api/model.html#Model.where()\" class=\"external\" target=\"_blank\"><code>where()</code></a> function, and we can chain all the parts of our query together using the dot operator (.) rather than adding them separately.\nThe code fragment below is the same as our query above, with an additional condition for the age.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>Athlete.find()\n .where(\"sport\")\n .equals(\"Tennis\")\n .where(\"age\")\n .gt(17)\n .lt(50) // Additional where query\n .limit(5)\n .sort({ age: -1 })\n .select(\"name age\")\n .exec();\n</code></pre></div>\n<p>The <a href=\"https://mongoosejs.com/docs/api/model.html#Model.find()\" class=\"external\" target=\"_blank\"><code>find()</code></a> method gets all matching records, but often you just want to get one match. The following methods query for a single record:</p>\n<ul>\n<li><a href=\"https://mongoosejs.com/docs/api/model.html#Model.findById()\" class=\"external\" target=\"_blank\"><code>findById()</code></a>: Finds the document with the specified <code>id</code> (every document has a unique <code>id</code>).</li>\n<li><a href=\"https://mongoosejs.com/docs/api/model.html#Model.findOne()\" class=\"external\" target=\"_blank\"><code>findOne()</code></a>: Finds a single document that matches the specified criteria.</li>\n<li><a href=\"https://mongoosejs.com/docs/api/model.html#Model.findByIdAndDelete()\" class=\"external\" target=\"_blank\"><code>findByIdAndDelete()</code></a>, <a href=\"https://mongoosejs.com/docs/api/model.html#Model.findByIdAndUpdate()\" class=\"external\" target=\"_blank\"><code>findByIdAndUpdate()</code></a>, <a href=\"https://mongoosejs.com/docs/api/model.html#Model.findOneAndRemove()\" class=\"external\" target=\"_blank\"><code>findOneAndRemove()</code></a>, <a href=\"https://mongoosejs.com/docs/api/model.html#Model.findOneAndUpdate()\" class=\"external\" target=\"_blank\"><code>findOneAndUpdate()</code></a>: Finds a single document by <code>id</code> or criteria and either updates or removes it. These are useful convenience functions for updating and removing records.</li>\n</ul>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nThere is also a <a href=\"https://mongoosejs.com/docs/api/model.html#Model.countDocuments()\" class=\"external\" target=\"_blank\"><code>countDocuments()</code></a> method that you can use to get the number of items that match conditions. This is useful if you want to perform a count without actually fetching the records.</p>\n</div>\n<p>There is a lot more you can do with queries. For more information see: <a href=\"https://mongoosejs.com/docs/queries.html\" class=\"external\" target=\"_blank\">Queries</a> (Mongoose docs).</p>\n<h4 id=\"working_with_related_documents_—_population\">Working with related documents — population</h4>\n<p>You can create references from one document/model instance to another using the <code>ObjectId</code> schema field, or from one document to many using an array of <code>ObjectIds</code>. The field stores the id of the related model. If you need the actual content of the associated document, you can use the <a href=\"https://mongoosejs.com/docs/populate.html\" class=\"external\" target=\"_blank\"><code>populate()</code></a> method in a query to replace the id with the actual data.</p>\n<p>For example, the following schema defines authors and stories.\nEach author can have multiple stories, which we represent as an array of <code>ObjectId</code>.\nEach story can have a single author.\nThe <code>ref</code> property tells the schema which model can be assigned to this field.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>const mongoose = require(\"mongoose\");\n\nconst Schema = mongoose.Schema;\n\nconst authorSchema = new Schema({\n name: String,\n stories: [{ type: Schema.Types.ObjectId, ref: \"Story\" }],\n});\n\nconst storySchema = new Schema({\n author: { type: Schema.Types.ObjectId, ref: \"Author\" },\n title: String,\n});\n\nconst Story = mongoose.model(\"Story\", storySchema);\nconst Author = mongoose.model(\"Author\", authorSchema);\n</code></pre></div>\n<p>We can save our references to the related document by assigning the <code>_id</code> value.\nBelow we create an author, then a story, and assign the author id to our story's author field.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>const bob = new Author({ name: \"Bob Smith\" });\n\nawait bob.save();\n\n// Bob now exists, so lets create a story\nconst story = new Story({\n title: \"Bob goes sledding\",\n author: bob._id, // assign the _id from our author Bob. This ID is created by default!\n});\n\nawait story.save();\n</code></pre></div>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nOne great benefit of this style of programming is that we don't have to complicate the main path of our code with error checking.\nIf any of the <code>save()</code> operations fail, the promise will reject and an error will be thrown.\nOur error handling code deals with that separately (usually in a <code>catch()</code> block), so the intent of our code is very clear.</p>\n</div>\n<p>Our story document now has an author referenced by the author document's ID. In order to get the author information in the story results we use <a href=\"https://mongoosejs.com/docs/api/model.html#Model.populate\" class=\"external\" target=\"_blank\"><code>populate()</code></a>, as shown below.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>Story.findOne({ title: \"Bob goes sledding\" })\n .populate(\"author\") // Replace the author id with actual author information in results\n .exec();\n</code></pre></div>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nAstute readers will have noted that we added an author to our story, but we didn't do anything to add our story to our author's <code>stories</code> array. How then can we get all stories by a particular author? One way would be to add our story to the stories array, but this would result in us having two places where the information relating authors and stories needs to be maintained.</p>\n<p>A better way is to get the <code>_id</code> of our <em>author</em>, then use <code>find()</code> to search for this in the author field across all stories.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>Story.find({ author: bob._id }).exec();\n</code></pre></div>\n</div>\n<p>This is almost everything you need to know about working with related items <em>for this tutorial</em>. For more detailed information see <a href=\"https://mongoosejs.com/docs/populate.html\" class=\"external\" target=\"_blank\">Population</a> (Mongoose docs).</p>"}},{"type":"prose","value":{"id":"one_schemamodel_per_file","title":"One schema/model per file","isH3":true,"content":"<p>While you can create schemas and models using any file structure you like, we highly recommend defining each model schema in its own module (file), then exporting the method to create the model.\nThis is shown below:</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>// File: ./models/some-model.js\n\n// Require Mongoose\nconst mongoose = require(\"mongoose\");\n\n// Define a schema\nconst Schema = mongoose.Schema;\n\nconst SomeModelSchema = new Schema({\n a_string: String,\n a_date: Date,\n});\n\n// Export function to create \"SomeModel\" model class\nmodule.exports = mongoose.model(\"SomeModel\", SomeModelSchema);\n</code></pre></div>\n<p>You can then require and use the model immediately in other files. Below we show how you might use it to get all instances of the model.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>// Create a SomeModel model just by requiring the module\nconst SomeModel = require(\"../models/some-model\");\n\n// Use the SomeModel object (model) to find all SomeModel records\nconst modelInstances = await SomeModel.find().exec();\n</code></pre></div>"}},{"type":"prose","value":{"id":"setting_up_the_mongodb_database","title":"Setting up the MongoDB database","isH3":false,"content":"<p>Now that we understand something of what Mongoose can do and how we want to design our models, it's time to start work on the <em>LocalLibrary</em> website. The very first thing we want to do is set up a MongoDB database that we can use to store our library data.</p>\n<p>For this tutorial, we're going to use the <a href=\"https://www.mongodb.com/products/platform/atlas-database\" class=\"external\" target=\"_blank\">MongoDB Atlas</a> cloud-hosted sandbox database. This database tier is not considered suitable for production websites because it has no redundancy, but it is great for development and prototyping. We're using it here because it is free and easy to set up, and because MongoDB Atlas is a popular <em>database as a service</em> vendor that you might reasonably choose for your production database (other popular choices at the time of writing include <a href=\"https://scalegrid.io/\" class=\"external\" target=\"_blank\">ScaleGrid</a> and <a href=\"https://www.objectrocket.com/\" class=\"external\" target=\"_blank\">ObjectRocket</a>).</p>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nIf you prefer, you can set up a MongoDB database locally by downloading and installing the <a href=\"https://www.mongodb.com/try/download/community-edition/releases\" class=\"external\" target=\"_blank\">appropriate binaries for your system</a>. The rest of the instructions in this article would be similar, except for the database URL you would specify when connecting.\nIn the <a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/deployment\">Express Tutorial Part 7: Deploying to Production</a> tutorial we host both the application and database on <a href=\"https://railway.app/\" class=\"external\" target=\"_blank\">Railway</a>, but we could equally well have used a database on <a href=\"https://www.mongodb.com/products/platform/atlas-database\" class=\"external\" target=\"_blank\">MongoDB Atlas</a>.</p>\n</div>\n<p>You will first need to <a href=\"https://www.mongodb.com/cloud/atlas/register\" class=\"external\" target=\"_blank\">create an account</a> with MongoDB Atlas (this is free, and just requires that you enter basic contact details and acknowledge their terms of service).</p>\n<p>After logging in, you'll be taken to the <a href=\"https://cloud.mongodb.com/v2\" class=\"external\" target=\"_blank\">home</a> screen:</p>\n<ol>\n<li>\n<p>Click the <strong>+ Create</strong> button in the <em>Overview</em> section.</p>\n<p><img src=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_createdatabase.jpg\" alt=\"Create a database on MongoDB Atlas.\" width=\"1667\" height=\"1174\" loading=\"lazy\"></p>\n</li>\n<li>\n<p>This will open the <em>Deploy your cluster</em> screen.\nClick on the <strong>M0 FREE</strong> option template.</p>\n<p><img src=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_deploy.jpg\" alt=\"Choose a deployment option when using MongoDB Atlas.\" width=\"1828\" height=\"879\" loading=\"lazy\"></p>\n</li>\n<li>\n<p>Scroll down the page to see the different options you can choose.\n<img src=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_createsharedcluster.jpg\" alt=\"Choose a cloud provider when using MongoDB Atlas.\" width=\"1683\" height=\"1235\" loading=\"lazy\"></p>\n<ul>\n<li>You can change the name of your Cluster under <em>Cluster Name</em>.\nWe are keeping it as <code>Cluster0</code> for this tutorial.</li>\n<li>Deselect the <em>Preload sample dataset</em> checkbox, as we'll import our own sample data later on</li>\n<li>Select any provider and region from the <em>Provider</em> and <em>Region</em> sections. Different regions offer different providers.</li>\n<li>Tags are optional. We will not use them here.</li>\n<li>Click the <strong>Create deployment</strong> button (creation of the cluster will take some minutes).</li>\n</ul>\n</li>\n<li>\n<p>This will open the <em>Security Quickstart</em> section.\n<img src=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_securityquickstart.jpg\" alt=\"Set up the Access Rules on the Security Quickstart screen on MongoDB Atlas.\" width=\"1939\" height=\"2721\" loading=\"lazy\"></p>\n<ul>\n<li>\n<p>Enter a username and password for your application to use to access the database (above we have created a new login \"cooluser\").\nRemember to copy and store the credentials safely as we will need them later on.\nClick the <strong>Create User</strong> button.</p>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nAvoid using special characters in your MongoDB user password as mongoose may not parse the connection string properly.</p>\n</div>\n</li>\n<li>\n<p>Select <strong>Add by current IP address</strong> to allow access from your current computer</p>\n</li>\n<li>\n<p>Enter <code>0.0.0.0/0</code> in the IP Address field and then click the <strong>Add Entry</strong> button.\nThis tells MongoDB that we want to allow access from anywhere.</p>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nIt is a best practice to limit the IP addresses that can connect to your database and other resources. Here we allow a connection from anywhere because we don't know where the request will come from after deployment.</p>\n</div>\n</li>\n<li>\n<p>Click the <strong>Finish and Close</strong> button.</p>\n</li>\n</ul>\n</li>\n<li>\n<p>This will open the following screen. Click on the <strong>Go to Overview</strong> button.\n<img src=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_accessrules.jpg\" alt=\"Go to Databases after setting up Access Rules on MongoDB Atlas\" width=\"1153\" height=\"431\" loading=\"lazy\"></p>\n</li>\n<li>\n<p>You will return to the <em>Overview</em> screen. Click on the <em>Database</em> section under the <em>Deployment</em> menu on the left. Click the <strong>Browse Collections</strong> button.\n<img src=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_createcollection.jpg\" alt=\"Setup a collection on MongoDB Atlas.\" width=\"2834\" height=\"1316\" loading=\"lazy\"></p>\n</li>\n<li>\n<p>This will open the <em>Collections</em> section. Click the <strong>Add My Own Data</strong> button.\n<img src=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_adddata.jpg\" alt=\"Create a database on MongoDB Atlas.\" width=\"1945\" height=\"1334\" loading=\"lazy\"></p>\n</li>\n<li>\n<p>This will open the <em>Create Database</em> screen.</p>\n<p><img src=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_databasedetails.jpg\" alt=\"Details during database creation on MongoDB Atlas.\" width=\"1206\" height=\"808\" loading=\"lazy\"></p>\n<ul>\n<li>Enter the name for the new database as <code>local_library</code>.</li>\n<li>Enter the name of the collection as <code>Collection0</code>.</li>\n<li>Click the <strong>Create</strong> button to create the database.</li>\n</ul>\n</li>\n<li>\n<p>You will return to the <em>Collections</em> screen with your database created.\n<img src=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_databasecreated.jpg\" alt=\"Database creation confirmation on MongoDB Atlas.\" width=\"1949\" height=\"1329\" loading=\"lazy\"></p>\n<ul>\n<li>Click the <em>Overview</em> tab to return to the cluster overview.</li>\n</ul>\n</li>\n<li>\n<p>From the Cluster0 <em>Overview</em> screen click the <strong>Connect</strong> button.</p>\n<p><img src=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_connectbutton.jpg\" alt=\"Configure connection after setting up a cluster in MongoDB Atlas.\" width=\"1949\" height=\"900\" loading=\"lazy\"></p>\n</li>\n<li>\n<p>This will open the <em>Connect to Cluster0</em> screen.</p>\n<p><img src=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/mongodb_atlas_-_connectforshortsrv.jpg\" alt=\"Choose the Short SRV connection when setting up a connection on MongoDB Atlas.\" width=\"2373\" height=\"1475\" loading=\"lazy\"></p>\n<ul>\n<li>Select your database user.</li>\n<li>Select the <em>Drivers</em> category, then the <em>Driver</em> <strong>Node.js</strong> and <em>Version</em> as shown.</li>\n<li><strong>DO NOT</strong> install the driver as suggested.</li>\n<li>Click the <strong>Copy</strong> icon to copy the connection string.</li>\n<li>Paste this in your local text editor.</li>\n<li>Replace <code>&lt;password&gt;</code> placeholder in the connection string with your user's password.</li>\n<li>Insert the database name \"local_library\" in the path before the options (<code>...mongodb.net/local_library?retryWrites...</code>)</li>\n<li>Save the file containing this string somewhere safe.</li>\n</ul>\n</li>\n</ol>\n<p>You have now created the database, and have a URL (with username and password) that can be used to access it.\nThis will look something like: <code>mongodb+srv://your_user_name:your_password@cluster0.cojoign.mongodb.net/local_library?retryWrites=true&amp;w=majority&amp;appName=Cluster0</code></p>"}},{"type":"prose","value":{"id":"install_mongoose","title":"Install Mongoose","isH3":false,"content":"<p>Open a command prompt and navigate to the directory where you created your <a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/skeleton_website\">skeleton Local Library website</a>.\nEnter the following command to install Mongoose (and its dependencies) and add it to your <strong>package.json</strong> file, unless you have already done so when reading the <a href=\"#installing_mongoose_and_mongodb\">Mongoose Primer</a> above.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">bash</span></div><pre class=\"brush: bash notranslate\"><code>npm install mongoose\n</code></pre></div>"}},{"type":"prose","value":{"id":"connect_to_mongodb","title":"Connect to MongoDB","isH3":false,"content":"<p>Open <strong>/app.js</strong> (in the root of your project) and copy the following text below where you declare the <em>Express application object</em> (after the line <code>const app = express();</code>).\nReplace the database URL string ('<em>insert_your_database_url_here</em>') with the location URL representing your own database (i.e. using the information from <em>MongoDB Atlas</em>).</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>// Set up mongoose connection\nconst mongoose = require(\"mongoose\");\nmongoose.set(\"strictQuery\", false);\nconst mongoDB = \"insert_your_database_url_here\";\n\nmain().catch((err) =&gt; console.log(err));\nasync function main() {\n await mongoose.connect(mongoDB);\n}\n</code></pre></div>\n<p>As discussed in the <a href=\"#connecting_to_mongodb\">Mongoose primer</a> above, this code creates the default connection to the database and reports any errors to the console.</p>\n<p>Note that hard-coding database credentials in source code as shown above is not recommended.\nWe do it here because it shows the core connection code, and because during development there is no significant risk that leaking these details will expose or corrupt sensitive information.\nWe'll show you how to do this more safely when <a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/deployment#database_configuration\">deploying to production</a>!</p>"}},{"type":"prose","value":{"id":"defining_the_locallibrary_schema","title":"Defining the LocalLibrary Schema","isH3":false,"content":"<p>We will define a separate module for each model, as <a href=\"#one_schemamodel_per_file\">discussed above</a>.\nStart by creating a folder for our models in the project root (<strong>/models</strong>) and then create separate files for each of the models:</p>\n<pre class=\"brush: plain notranslate\">/express-locallibrary-tutorial // the project root\n /models\n author.js\n book.js\n bookinstance.js\n genre.js\n</pre>"}},{"type":"prose","value":{"id":"author_model","title":"Author model","isH3":true,"content":"<p>Copy the <code>Author</code> schema code shown below and paste it into your <strong>./models/author.js</strong> file.\nThe schema defines an author as having <code>String</code> SchemaTypes for the first and family names (required, with a maximum of 100 characters), and <code>Date</code> fields for the dates of birth and death.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>const mongoose = require(\"mongoose\");\n\nconst Schema = mongoose.Schema;\n\nconst AuthorSchema = new Schema({\n first_name: { type: String, required: true, maxLength: 100 },\n family_name: { type: String, required: true, maxLength: 100 },\n date_of_birth: { type: Date },\n date_of_death: { type: Date },\n});\n\n// Virtual for author's full name\nAuthorSchema.virtual(\"name\").get(function () {\n // To avoid errors in cases where an author does not have either a family name or first name\n // We want to make sure we handle the exception by returning an empty string for that case\n let fullname = \"\";\n if (this.first_name &amp;&amp; this.family_name) {\n fullname = `${this.family_name}, ${this.first_name}`;\n }\n\n return fullname;\n});\n\n// Virtual for author's URL\nAuthorSchema.virtual(\"url\").get(function () {\n // We don't use an arrow function as we'll need the this object\n return `/catalog/author/${this._id}`;\n});\n\n// Export model\nmodule.exports = mongoose.model(\"Author\", AuthorSchema);\n</code></pre></div>\n<p>We've also declared a <a href=\"#virtual_properties\">virtual</a> for the AuthorSchema named \"url\" that returns the absolute URL required to get a particular instance of the model — we'll use the property in our templates whenever we need to get a link to a particular author.</p>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nDeclaring our URLs as a virtual in the schema is a good idea because then the URL for an item only ever needs to be changed in one place.\nAt this point, a link using this URL wouldn't work, because we haven't got any routes handling code for individual model instances.\nWe'll set those up in a later article!</p>\n</div>\n<p>At the end of the module, we export the model.</p>"}},{"type":"prose","value":{"id":"book_model","title":"Book model","isH3":true,"content":"<p>Copy the <code>Book</code> schema code shown below and paste it into your <strong>./models/book.js</strong> file.\nMost of this is similar to the author model — we've declared a schema with a number of string fields and a virtual for getting the URL of specific book records, and we've exported the model.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>const mongoose = require(\"mongoose\");\n\nconst Schema = mongoose.Schema;\n\nconst BookSchema = new Schema({\n title: { type: String, required: true },\n author: { type: Schema.Types.ObjectId, ref: \"Author\", required: true },\n summary: { type: String, required: true },\n isbn: { type: String, required: true },\n genre: [{ type: Schema.Types.ObjectId, ref: \"Genre\" }],\n});\n\n// Virtual for book's URL\nBookSchema.virtual(\"url\").get(function () {\n // We don't use an arrow function as we'll need the this object\n return `/catalog/book/${this._id}`;\n});\n\n// Export model\nmodule.exports = mongoose.model(\"Book\", BookSchema);\n</code></pre></div>\n<p>The main difference here is that we've created two references to other models:</p>\n<ul>\n<li>author is a reference to a single <code>Author</code> model object, and is required.</li>\n<li>genre is a reference to an array of <code>Genre</code> model objects. We haven't declared this object yet!</li>\n</ul>"}},{"type":"prose","value":{"id":"bookinstance_model","title":"BookInstance model","isH3":true,"content":"<p>Finally, copy the <code>BookInstance</code> schema code shown below and paste it into your <strong>./models/bookinstance.js</strong> file.\nThe <code>BookInstance</code> represents a specific copy of a book that someone might borrow and includes information about whether the copy is available, on what date it is expected back, and \"imprint\" (or version) details.</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">js</span></div><pre class=\"brush: js notranslate\"><code>const mongoose = require(\"mongoose\");\n\nconst Schema = mongoose.Schema;\n\nconst BookInstanceSchema = new Schema({\n book: { type: Schema.Types.ObjectId, ref: \"Book\", required: true }, // reference to the associated book\n imprint: { type: String, required: true },\n status: {\n type: String,\n required: true,\n enum: [\"Available\", \"Maintenance\", \"Loaned\", \"Reserved\"],\n default: \"Maintenance\",\n },\n due_back: { type: Date, default: Date.now },\n});\n\n// Virtual for bookinstance's URL\nBookInstanceSchema.virtual(\"url\").get(function () {\n // We don't use an arrow function as we'll need the this object\n return `/catalog/bookinstance/${this._id}`;\n});\n\n// Export model\nmodule.exports = mongoose.model(\"BookInstance\", BookInstanceSchema);\n</code></pre></div>\n<p>The new things we show here are the field options:</p>\n<ul>\n<li><code>enum</code>: This allows us to set the allowed values of a string. In this case, we use it to specify the availability status of our books (using an enum means that we can prevent mis-spellings and arbitrary values for our status).</li>\n<li><code>default</code>: We use default to set the default status for newly created book instances to \"Maintenance\" and the default <code>due_back</code> date to <code>now</code> (note how you can call the Date function when setting the date!).</li>\n</ul>\n<p>Everything else should be familiar from our previous schema.</p>"}},{"type":"prose","value":{"id":"genre_model_-_challenge","title":"Genre model - challenge","isH3":true,"content":"<p>Open your <strong>./models/genre.js</strong> file and create a schema for storing genres (the category of book, e.g. whether it is fiction or non-fiction, romance or military history, etc.).</p>\n<p>The definition will be very similar to the other models:</p>\n<ul>\n<li>The model should have a <code>String</code> SchemaType called <code>name</code> to describe the genre.</li>\n<li>This name should be required and have between 3 and 100 characters.</li>\n<li>Declare a <a href=\"#virtual_properties\">virtual</a> for the genre's URL, named <code>url</code>.</li>\n<li>Export the model.</li>\n</ul>"}},{"type":"prose","value":{"id":"testing_—_create_some_items","title":"Testing — create some items","isH3":false,"content":"<p>That's it. We now have all models for the site set up!</p>\n<p>In order to test the models (and to create some example books and other items that we can use in our next articles) we'll now run an <em>independent</em> script to create items of each type:</p>\n<ol>\n<li>\n<p>Download (or otherwise create) the file <a href=\"https://raw.githubusercontent.com/mdn/express-locallibrary-tutorial/main/populatedb.js\" class=\"external\" target=\"_blank\">populatedb.js</a> inside your <em>express-locallibrary-tutorial</em> directory (in the same level as <code>package.json</code>).</p>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nThe code in <code>populatedb.js</code> may be useful in learning JavaScript, but understanding it is not necessary for this tutorial.</p>\n</div>\n</li>\n<li>\n<p>Run the script using node in your command prompt, passing in the URL of your <em>MongoDB</em> database (the same one you replaced the <em>insert_your_database_url_here</em> placeholder with, inside <code>app.js</code> earlier):</p>\n<div class=\"code-example\"><div class=\"example-header\"><span class=\"language-name\">bash</span></div><pre class=\"brush: bash notranslate\"><code>node populatedb &lt;your MongoDB url&gt;\n</code></pre></div>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nOn Windows you need to wrap the database URL inside double (\").\nOn other operating systems you may need single (') quotation marks.</p>\n</div>\n</li>\n<li>\n<p>The script should run through to completion, displaying items as it creates them in the terminal.</p>\n</li>\n</ol>\n<div class=\"notecard note\">\n<p><strong>Note:</strong>\nGo to your database on MongoDB Atlas (in the <em>Collections</em> tab).\nYou should now be able to drill down into individual collections of Books, Authors, Genres and BookInstances, and check out individual documents.</p>\n</div>"}},{"type":"prose","value":{"id":"summary","title":"Summary","isH3":false,"content":"<p>In this article, we've learned a bit about databases and ORMs on Node/Express, and a lot about how Mongoose schema and models are defined. We then used this information to design and implement <code>Book</code>, <code>BookInstance</code>, <code>Author</code> and <code>Genre</code> models for the <em>LocalLibrary</em> website.</p>\n<p>Last of all, we tested our models by creating a number of instances (using a standalone script). In the next article we'll look at creating some pages to display these objects.</p>"}},{"type":"prose","value":{"id":"see_also","title":"See also","isH3":false,"content":"<ul>\n<li><a href=\"https://expressjs.com/en/guide/database-integration.html\" class=\"external\" target=\"_blank\">Database integration</a> (Express docs)</li>\n<li><a href=\"https://mongoosejs.com/\" class=\"external\" target=\"_blank\">Mongoose website</a> (Mongoose docs)</li>\n<li><a href=\"https://mongoosejs.com/docs/guide.html\" class=\"external\" target=\"_blank\">Mongoose Guide</a> (Mongoose docs)</li>\n<li><a href=\"https://mongoosejs.com/docs/validation.html\" class=\"external\" target=\"_blank\">Validation</a> (Mongoose docs)</li>\n<li><a href=\"https://mongoosejs.com/docs/schematypes.html\" class=\"external\" target=\"_blank\">Schema Types</a> (Mongoose docs)</li>\n<li><a href=\"https://mongoosejs.com/docs/models.html\" class=\"external\" target=\"_blank\">Models</a> (Mongoose docs)</li>\n<li><a href=\"https://mongoosejs.com/docs/queries.html\" class=\"external\" target=\"_blank\">Queries</a> (Mongoose docs)</li>\n<li><a href=\"https://mongoosejs.com/docs/populate.html\" class=\"external\" target=\"_blank\">Population</a> (Mongoose docs)</li>\n</ul>\n<ul class=\"prev-next\"><li><a class=\"button secondary\" href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/skeleton_website\"><span class=\"button-wrap\"> Previous </span></a></li><li><a class=\"button secondary\" href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs\"><span class=\"button-wrap\"> Overview: Express web framework (Node.js/JavaScript)</span></a></li><li><a class=\"button secondary\" href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/routes\"><span class=\"button-wrap\"> Next </span></a></li></ul>"}}],"isActive":true,"isMarkdown":true,"isTranslated":false,"locale":"en-US","mdn_url":"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose","modified":"2024-12-19T15:37:45.000Z","native":"English (US)","noIndexing":false,"other_translations":[{"locale":"de","title":"Express-Tutorial Teil 3: Verwendung einer Datenbank (mit Mongoose)","native":"Deutsch"},{"locale":"ja","title":"Express チュートリアル Part 3: データベースの使用 (Mongoose を使用)","native":"日本語"},{"locale":"pt-BR","title":"Tutorial Express Parte 3: Usando um banco de dados (com Mongoose)","native":"Português (do Brasil)"},{"locale":"ru","title":"Учебник Express часть 3: Использование базы данных (с помощью Mongoose)","native":"Русский"},{"locale":"zh-CN","title":"Express 教程 3:使用数据库 (Mongoose)","native":"中文 (简体)"},{"locale":"zh-TW","title":"Express 教學 3:使用資料庫(Mongoose)","native":"正體中文 (繁體)"}],"pageTitle":"Express Tutorial Part 3: Using a Database (with Mongoose) - Learn web development | MDN","parents":[{"uri":"/en-US/docs/Learn_web_development","title":"Learn"},{"uri":"/en-US/docs/Learn_web_development/Extensions","title":"Extension modules"},{"uri":"/en-US/docs/Learn_web_development/Extensions/Server-side","title":"Server-side website programming"},{"uri":"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs","title":"Express web framework (Node.js/JavaScript)"},{"uri":"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose","title":"Express Tutorial Part 3: Using a Database (with Mongoose)"}],"popularity":null,"short_title":"Express Tutorial Part 3: Using a Database (with Mongoose)","sidebarHTML":"<ol><li class=\"section\"><a href=\"/en-US/docs/Learn_web_development/Getting_started\">Getting started modules</a></li><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Getting_started/Environment_setup\">Environment setup</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Getting_started/Environment_setup/Installing_software\">Installing basic software</a></li><li><a href=\"/en-US/docs/Learn_web_development/Getting_started/Environment_setup/Browsing_the_web\">Browsing the web</a></li><li><a href=\"/en-US/docs/Learn_web_development/Getting_started/Environment_setup/Code_editors\">Code editors</a></li><li><a href=\"/en-US/docs/Learn_web_development/Getting_started/Environment_setup/Dealing_with_files\">Dealing with files</a></li><li><a href=\"/en-US/docs/Learn_web_development/Getting_started/Environment_setup/Command_line\">Command line crash course</a></li></ol></details></li><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Getting_started/Your_first_website\">Your first website</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Getting_started/Your_first_website/What_will_your_website_look_like\">What will your website look like?</a></li><li><a href=\"/en-US/docs/Learn_web_development/Getting_started/Your_first_website/Creating_the_content\">HTML: Creating the content</a></li><li><a href=\"/en-US/docs/Learn_web_development/Getting_started/Your_first_website/Styling_the_content\">CSS: Styling the content</a></li><li><a href=\"/en-US/docs/Learn_web_development/Getting_started/Your_first_website/Adding_interactivity\">JavaScript: Adding interactivity</a></li><li><a href=\"/en-US/docs/Learn_web_development/Getting_started/Your_first_website/Publishing_your_website\">Publishing your website</a></li></ol></details></li><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Getting_started/Web_standards\">Web standards</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Getting_started/Web_standards/How_the_web_works\">How the web works</a></li><li><a href=\"/en-US/docs/Learn_web_development/Getting_started/Web_standards/The_web_standards_model\">The web standards model</a></li><li><a href=\"/en-US/docs/Learn_web_development/Getting_started/Web_standards/How_browsers_load_websites\">How browsers load websites</a></li></ol></details></li><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Getting_started/Soft_skills\">Soft skills</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Getting_started/Soft_skills/Research_and_learning\">Research and learning</a></li><li><a href=\"/en-US/docs/Learn_web_development/Getting_started/Soft_skills/Collaboration_and_teamwork\">Collaboration and teamwork</a></li><li><a href=\"/en-US/docs/Learn_web_development/Getting_started/Soft_skills/Workflows_and_processes\">Workflows and processes</a></li><li><a href=\"/en-US/docs/Learn_web_development/Getting_started/Soft_skills/Job_interviews\">Succeeding in job interviews</a></li></ol></details></li><li class=\"section\"><a href=\"/en-US/docs/Learn_web_development/Core\">Core modules</a></li><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Core/Structuring_content\">Structuring content with HTML</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Core/Structuring_content/Basic_HTML_syntax\">Basic HTML syntax</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Structuring_content/Webpage_metadata\">What's in the head? Webpage metadata</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Structuring_content/Headings_and_paragraphs\">Headings and paragraphs in HTML</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Structuring_content/Emphasis_and_importance\">Emphasis and importance</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Structuring_content/Lists\">Lists</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Structuring_content/Structuring_documents\">Structuring documents</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Structuring_content/Advanced_text_features\">Advanced text features</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Structuring_content/Creating_links\">Creating links</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Structuring_content/Marking_up_a_letter\">Challenge: Marking up a letter</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Structuring_content/Structuring_a_page_of_content\">Challenge: Structuring a page of content</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Structuring_content/HTML_images\">HTML images</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Structuring_content/HTML_video_and_audio\">HTML video and audio</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Structuring_content/Mozilla_splash_page\">Challenge: Mozilla splash page</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Structuring_content/HTML_table_basics\">HTML table basics</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Structuring_content/Table_accessibility\">HTML table accessibility</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Structuring_content/Planet_data_table\">Challenge: Structuring a planet data table</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Structuring_content/HTML_forms\">Forms and buttons in HTML</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Structuring_content/Debugging_HTML\">Debugging HTML</a></li></ol></details></li><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Core/Styling_basics\">CSS styling basics</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Core/Styling_basics/What_is_CSS\">What is CSS?</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Styling_basics/Getting_started\">Getting started with CSS</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Styling_basics/Styling_a_bio_page\">Challenge: Styling a biography page</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Styling_basics/Basic_selectors\">Basic CSS selectors</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Styling_basics/Attribute_selectors\">Attribute selectors</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Styling_basics/Pseudo_classes_and_elements\">Pseudo-classes and pseudo-elements</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Styling_basics/Combinators\">Combinators</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Styling_basics/Box_model\">The box model</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Styling_basics/Handling_conflicts\">Handling conflicts</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Styling_basics/Values_and_units\">CSS values and units</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Styling_basics/Sizing\">Sizing items in CSS</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Styling_basics/Backgrounds_and_borders\">Backgrounds and borders</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Styling_basics/Overflow\">Overflowing content</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Styling_basics/Images_media_forms\">Images, media, and form elements</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Styling_basics/Tables\">Styling tables</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Styling_basics/Debugging_CSS\">Debugging CSS</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Styling_basics/Fundamental_CSS_comprehension\">Challenge: Fundamental CSS comprehension</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Styling_basics/Fancy_letterheaded_paper\">Challenge: Creating fancy letterheaded paper</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Styling_basics/Cool-looking_box\">Challenge: A cool-looking box</a></li></ol></details></li><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Core/Text_styling\">CSS text styling</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Core/Text_styling/Fundamentals\">Fundamental text and font styling</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Text_styling/Styling_lists\">Styling lists</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Text_styling/Styling_links\">Styling links</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Text_styling/Web_fonts\">Web fonts</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Text_styling/Typesetting_a_homepage\">Challenge: Typesetting a community school homepage</a></li></ol></details></li><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Core/CSS_layout\">CSS layout</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Core/CSS_layout/Introduction\">Introduction to CSS layout</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/CSS_layout/Floats\">Floats</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/CSS_layout/Positioning\">Positioning</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/CSS_layout/Flexbox\">Flexbox</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/CSS_layout/Grids\">CSS grid layout</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/CSS_layout/Responsive_Design\">Responsive design</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/CSS_layout/Media_queries\">Media query fundamentals</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/CSS_layout/Fundamental_Layout_Comprehension\">Challenge: Fundamental layout comprehension</a></li></ol></details></li><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Core/Scripting\">Dynamic scripting with JavaScript</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/What_is_JavaScript\">What is JavaScript?</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/A_first_splash\">A first splash into JavaScript</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/What_went_wrong\">What went wrong? Troubleshooting JavaScript</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/Variables\">Storing the information you need — Variables</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/Math\">Basic math in JavaScript — numbers and operators</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/Strings\">Handling text — strings in JavaScript</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/Useful_string_methods\">Useful string methods</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/Arrays\">Arrays</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/Silly_story_generator\">Challenge: Silly story generator</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/Conditionals\">Making decisions in your code — conditionals</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/Loops\">Looping code</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/Functions\">Functions — reusable blocks of code</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/Build_your_own_function\">Build your own function</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/Return_values\">Function return values</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/Events\">Introduction to events</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/Event_bubbling\">Event bubbling</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/Image_gallery\">Challenge: Image gallery</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/Object_basics\">JavaScript object basics</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/DOM_scripting\">DOM scripting introduction</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/Network_requests\">Making network requests with JavaScript</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/JSON\">Working with JSON</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Scripting/Debugging_JavaScript\">Debugging JavaScript and handling errors</a></li></ol></details></li><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Core/Frameworks_libraries\">JavaScript frameworks and libraries</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Core/Frameworks_libraries/Introduction\">Introduction to client-side frameworks</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Frameworks_libraries/Main_features\">Framework main features</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Frameworks_libraries/React_getting_started\">Getting started with React</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Frameworks_libraries/React_todo_list_beginning\">Beginning our React todo list</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Frameworks_libraries/React_components\">Componentizing our React app</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Frameworks_libraries/React_interactivity_events_state\">React interactivity: Events and state</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Frameworks_libraries/React_interactivity_filtering_conditional_rendering\">React interactivity: Editing, filtering, conditional rendering</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Frameworks_libraries/React_accessibility\">Accessibility in React</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Frameworks_libraries/React_resources\">React resources</a></li></ol></details></li><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Core/Accessibility\">Accessibility</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Core/Accessibility/What_is_accessibility\">What is accessibility?</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Accessibility/Tooling\">Accessibility tooling and assistive technology</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Accessibility/HTML\">HTML: A good basis for accessibility</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Accessibility/CSS_and_JavaScript\">CSS and JavaScript accessibility best practices</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Accessibility/WAI-ARIA_basics\">WAI-ARIA basics</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Accessibility/Multimedia\">Accessible multimedia</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Accessibility/Mobile\">Mobile accessibility</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Accessibility/Accessibility_troubleshooting\">Challenge: Accessibility troubleshooting</a></li></ol></details></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Design_for_developers\">Design for developers</a></li><li><a href=\"/en-US/docs/Learn_web_development/Core/Version_control\">Version control</a></li><li class=\"section\"><a href=\"/en-US/docs/Learn_web_development/Extensions\">Extension modules</a></li><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Extensions/Advanced_JavaScript_objects\">Advanced JavaScript objects</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Advanced_JavaScript_objects/Object_prototypes\">Object prototypes</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Advanced_JavaScript_objects/Object-oriented_programming\">Object-oriented programming</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Advanced_JavaScript_objects/Classes_in_JavaScript\">Classes in JavaScript</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Advanced_JavaScript_objects/Object_building_practice\">Object building practice</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Advanced_JavaScript_objects/Adding_bouncing_balls_features\">Challenge: Adding features to our bouncing balls demo</a></li></ol></details></li><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Extensions/Client-side_APIs\">Client-side web APIs</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Client-side_APIs/Introduction\">Introduction to web APIs</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Client-side_APIs/Video_and_audio_APIs\">Video and Audio APIs</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Client-side_APIs/Drawing_graphics\">Drawing graphics</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Client-side_APIs/Client-side_storage\">Client-side storage</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Client-side_APIs/Third_party_APIs\">Third-party APIs</a></li></ol></details></li><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Extensions/Async_JS\">Asynchronous JavaScript</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Async_JS/Introducing\">Introducing asynchronous JavaScript</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Async_JS/Promises\">How to use promises</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Async_JS/Implementing_a_promise-based_API\">How to implement a promise-based API</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Async_JS/Introducing_workers\">Introducing workers</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Async_JS/Sequencing_animations\">Challenge: Sequencing animations</a></li></ol></details></li><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Extensions/Forms\">Web forms</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Forms/Your_first_form\">Your first form</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Forms/How_to_structure_a_web_form\">How to structure a web form</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Forms/Basic_native_form_controls\">Basic native form controls</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Forms/HTML5_input_types\">The HTML5 input types</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Forms/Other_form_controls\">Other form controls</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Forms/Styling_web_forms\">Styling web forms</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Forms/Advanced_form_styling\">Advanced form styling</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Forms/UI_pseudo-classes\">UI pseudo-classes</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Forms/Form_validation\">Client-side form validation</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Forms/Sending_and_retrieving_form_data\">Sending form data</a></li></ol></details></li><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Extensions/Client-side_tools\">Understanding client-side tools</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Client-side_tools/Overview\">Client-side tooling overview</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Client-side_tools/Package_management\">Package management basics</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Client-side_tools/Introducing_complete_toolchain\">Introducing a complete toolchain</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Client-side_tools/Deployment\">Deploying our app</a></li></ol></details></li><li class=\"toggle\"><details open=\"\"><summary><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side\">Server-side websites</a></summary><ol><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/First_steps\">Server-side first steps</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/First_steps/Introduction\">Introduction to the server side</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/First_steps/Client-Server_overview\">Client-Server Overview</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/First_steps/Web_frameworks\">Server-side web frameworks</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/First_steps/Website_security\">Website security</a></li></ol></details></li><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Django\">Django web framework (Python)</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Introduction\">Django introduction</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Django/development_environment\">Setting up a Django development environment</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Tutorial_local_library_website\">Django Tutorial: The Local Library website</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Django/skeleton_website\">Django Tutorial Part 2: Creating a skeleton website</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Models\">Django Tutorial Part 3: Using models</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Admin_site\">Django Tutorial Part 4: Django admin site</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Home_page\">Django Tutorial Part 5: Creating our home page</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Generic_views\">Django Tutorial Part 6: Generic list and detail views</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Sessions\">Django Tutorial Part 7: Sessions framework</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Authentication\">Django Tutorial Part 8: User authentication and permissions</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Forms\">Django Tutorial Part 9: Working with forms</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Testing\">Django Tutorial Part 10: Testing a Django web application</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Django/Deployment\">Django Tutorial Part 11: Deploying Django to production</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Django/web_application_security\">Django web application security</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Django/django_assessment_blog\">Assessment: DIY Django mini blog</a></li></ol></details></li><li class=\"toggle\"><details open=\"\"><summary><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs\">Express web framework (Node.js)</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Introduction\">Express/Node introduction</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/development_environment\">Setting up a Node development environment</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Tutorial_local_library_website\">Express Tutorial: The Local Library website</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/skeleton_website\">Express Tutorial Part 2: Creating a skeleton website</a></li><li><em><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose\" aria-current=\"page\">Express Tutorial Part 3: Using a Database (with Mongoose)</a></em></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/routes\">Express Tutorial Part 4: Routes and controllers</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Displaying_data\">Express Tutorial Part 5: Displaying library data</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/forms\">Express Tutorial Part 6: Working with forms</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/deployment\">Express Tutorial Part 7: Deploying to production</a></li></ol></details></li></ol></details></li><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Extensions/Performance\">Web performance</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Performance/why_web_performance\">The \"why\" of web performance</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Performance/What_is_web_performance\">What is web performance?</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Performance/Perceived_performance\">Perceived performance</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Performance/Measuring_performance\">Measuring performance</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Performance/Multimedia\">Multimedia: Images</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Performance/video\">Multimedia: video</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Performance/JavaScript\">JavaScript performance optimization</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Performance/HTML\">HTML performance optimization</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Performance/CSS\">CSS performance optimization</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Performance/business_case_for_performance\">The business case for web performance</a></li></ol></details></li><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Extensions/Testing\">Testing</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Testing/Introduction\">Introduction to cross-browser testing</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Testing/Testing_strategies\">Strategies for carrying out testing</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Testing/HTML_and_CSS\">Handling common HTML and CSS problems</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Testing/Feature_detection\">Implementing feature detection</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Testing/Automated_testing\">Introduction to automated testing</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Testing/Your_own_automation_environment\">Setting up your own test automation environment</a></li></ol></details></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Transform_animate\">Transform and animate CSS</a></li><li><a href=\"/en-US/docs/Learn_web_development/Extensions/Security_privacy\">Security and privacy</a></li><li class=\"section\">Further resources</li><li class=\"toggle\"><details><summary><a href=\"/en-US/docs/Learn_web_development/Howto\">How to solve common problems</a></summary><ol><li><a href=\"/en-US/docs/Learn_web_development/Howto/Solve_HTML_problems\">Solve common HTML problems</a></li><li><a href=\"/en-US/docs/Learn_web_development/Howto/Solve_CSS_problems\">Solve common CSS problems</a></li><li><a href=\"/en-US/docs/Learn_web_development/Howto/Solve_JavaScript_problems\">Solve common JavaScript problems</a></li><li><a href=\"/en-US/docs/Learn_web_development/Howto/Web_mechanics\">Web mechanics</a></li><li><a href=\"/en-US/docs/Learn_web_development/Howto/Tools_and_setup\">Tools and setup</a></li><li><a href=\"/en-US/docs/Learn_web_development/Howto/Design_and_accessibility\">Design and accessibility</a></li></ol></details></li><li><a href=\"/en-US/docs/Learn_web_development/About\">About</a></li><li><a href=\"/en-US/docs/Learn_web_development/Educators\">Resources for educators</a></li><li><a href=\"/en-US/docs/Learn_web_development/Changelog\">Changelog</a></li></ol>","source":{"folder":"en-us/learn_web_development/extensions/server-side/express_nodejs/mongoose","github_url":"https://github.com/mdn/content/blob/main/files/en-us/learn_web_development/extensions/server-side/express_nodejs/mongoose/index.md","last_commit_url":"https://github.com/mdn/content/commit/5b20f5f4265f988f80f513db0e4b35c7e0cd70dc","filename":"index.md"},"summary":"This article briefly introduces databases, and how to use them with Node/Express apps. It then goes on to show how we can use Mongoose to provide database access for the LocalLibrary website. It explains how object schema and models are declared, the main field types, and basic validation. It also briefly shows a few of the main ways in which you can access model data.","title":"Express Tutorial Part 3: Using a Database (with Mongoose)","toc":[{"text":"Overview","id":"overview"},{"text":"Designing the LocalLibrary models","id":"designing_the_locallibrary_models"},{"text":"Mongoose primer","id":"mongoose_primer"},{"text":"Setting up the MongoDB database","id":"setting_up_the_mongodb_database"},{"text":"Install Mongoose","id":"install_mongoose"},{"text":"Connect to MongoDB","id":"connect_to_mongodb"},{"text":"Defining the LocalLibrary Schema","id":"defining_the_locallibrary_schema"},{"text":"Testing — create some items","id":"testing_—_create_some_items"},{"text":"Summary","id":"summary"},{"text":"See also","id":"see_also"}],"pageType":"learn-module-chapter"}}</script></body></html>

Pages: 1 2 3 4 5 6 7 8 9 10