Complete Guide for using Typescript in Mongoose with lean() function

  • Writing the minimal code necessary
  • Using the lean() function
  • References between model

TLDR; The Code;

You don’t need @types/mongoose

yarn add mongoose

The Model vs the Doc Instance

Rule #1: Use Lean Whenever You Can

  • It comes with a price. There is overhead.
  • You don’t need it most of the time.
  • You need to be very clear where you are dealing with the database operation. It’s always a good idea to isolate database operation in a specific area of your code. Once you are done with it, you get out of it. Bringing the document instance to other modules/layers of your code may result in unexpected side effect. It’s messy and hard to debug.

Rule #2: Don’t use virtual and instance method

Type Explain: DocPoJo

UserPoJo is the minimum you need when you create a document

Type Explain: Doc

The UserDoc instance is returned from the model. It is tracking changes and you can do database operation like update() here.

Type Explain: User Model

Type Explain: DocLean

The lean instance has all properties inherited from the PoJo type and also the _id property.

The Reference

Notice that we are using the lean type for user here, so that it gives us back a nice POJO.

Conclusion

To Do

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Corona Time Pass became Brainbite

The Snowpack — Next-generation build tool

Javascript & ` console.log`

Up your DOM manipulation game through these Exercises-Part 01 📚

Implement the Async/Await Pattern and be Familiar with the Generator

Blog Prompt #201

Node Package Manager

React Responsive Slider

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jason Ching

Jason Ching

More from Medium

Heroku — Schedule Python with Mongo DB for Data refresh

Layer-2 Blockchain Scaling

Creating Project/Bug Tracker [Part 1] — Login Create Account Frontend

A Quick request