banner



How To Update Child Schema In Moongoose And Save Parent Schema

Mongoose 101: Working with subdocuments

18th Dec 2019

You learned how to use Mongoose on a basic level to create, read, update, and delete documents in the previous tutorial. In this tutorial, we'll go a pace further into subdocuments

What'southward a subdocument

In Mongoose, subdocuments are documents that are nested in other documents. You can spot a subdocument when a schema is nested in another schema.

Annotation: MongoDB calls subdocuments embedded documents.

          const childSchema = new Schema({   proper name: String });  const parentSchema = new Schema({   // Single subdocument   kid: childSchema,    // Array of subdocuments   children: [ childSchema ] });                  

In practice, you don't have to create a split up childSchema like the example above. Mongoose helps you create nested schemas when you nest an object in some other object.

          // This code is the aforementioned as above const parentSchema = new Schema({   // Single subdocument   child: { name: String },    // Array of subdocuments   children: [{name: String }] });                  

Updating characterSchema

Permit'due south say we desire to create a character called Ryu. Ryu has three special moves.

  1. Hadoken
  2. Shinryuken
  3. Tatsumaki Senpukyaku

Ryu besides has one ultimate move called:

  1. Shinku Hadoken

We want to save the names of each movement. Nosotros also want to save the keys required to execute that move.

Here, each motion is a subdocument.

          const characterSchema = new Schema({   name: { blazon: String, unique: true },   // Array of subdocuments   specials: [{     name: String,     keys: Cord   }]   // Single subdocument   ultimate: {     proper noun: String,     keys: String   } })                  

You tin can also use the childSchema syntax if y'all wish to. It makes the Graphic symbol schema easier to sympathize.

          const moveSchema = new Schema({   proper name: String,   keys: String })  const characterSchema = new Schema({   proper noun: { type: Cord, unique: true },   // Array of subdocuments   specials: [moveSchema],   // Single subdocument   ultimate: moveSchema })                  

Creating documents that contain subdocuments

In that location are two means to create documents that contain subdocuments:

  1. Laissez passer a nested object into new Model
  2. Add properties into the created document.

Method 1: Passing the entire object

For this method, we construct a nested object that contains both Ryu's name and his moves.

          const ryu = {   name: 'Ryu',   specials: [{     proper name: 'Hadoken',     keys: '↓ ↘ → P'   }, {     name: 'Shoryuken',     keys: '→ ↓ ↘ → P'   }, {     name: 'Tatsumaki Senpukyaku',     keys: '↓ ↙ ← Grand'   }],   ultimate: {     proper name: 'Shinku Hadoken',     keys: '↓ ↘ → ↓ ↘ → P'   } }                  

Then, we pass this object into new Character.

          const char = new Character(ryu) const dr. = await char.salvage() console.log(doc)                  
Image of Ryu's document.

Method 2: Adding subdocuments afterward

For this method, we create a grapheme with new Character get-go.

          const ryu = new Character({ proper name: 'Ryu' })                  

Then, nosotros edit the graphic symbol to add special moves:

          const ryu = new Character({ name: 'Ryu' }) const ryu.specials = [{   proper name: 'Hadoken',   keys: '↓ ↘ → P' }, {   proper name: 'Shoryuken',   keys: '→ ↓ ↘ → P' }, {   name: 'Tatsumaki Senpukyaku',   keys: '↓ ↙ ← Thousand' }]                  

Then, we edit the character to add the ultimate move:

          const ryu = new Grapheme({ name: 'Ryu' })  // Adds specials const ryu.specials = [{   name: 'Hadoken',   keys: '↓ ↘ → P' }, {   proper noun: 'Shoryuken',   keys: '→ ↓ ↘ → P' }, {   name: 'Tatsumaki Senpukyaku',   keys: '↓ ↙ ← K' }]  // Adds ultimate ryu.ultimate = {   proper name: 'Shinku Hadoken',   keys: '↓ ↘ → ↓ ↘ → P' }                  

Once we're satisfied with ryu, we run salvage.

          const ryu = new Character({ name: 'Ryu' })  // Adds specials const ryu.specials = [{   name: 'Hadoken',   keys: '↓ ↘ → P' }, {   name: 'Shoryuken',   keys: '→ ↓ ↘ → P' }, {   proper name: 'Tatsumaki Senpukyaku',   keys: '↓ ↙ ← K' }]  // Adds ultimate ryu.ultimate = {   name: 'Shinku Hadoken',   keys: '↓ ↘ → ↓ ↘ → P' }  const doc = await ryu.salve() panel.log(doc)                  
Image of Ryu's document.

Updating assortment subdocuments

The easiest way to update subdocuments is:

  1. Use findOne to find the document
  2. Get the array
  3. Change the assortment
  4. Run save

For example, let's say we want to add Jodan Sokutou Geri to Ryu'southward special moves. The keys for Jodan Sokutou Geri are ↓ ↘ → K.

Kickoff, we detect Ryu with findOne.

          const ryu = expect Characters.findOne({ name: 'Ryu' })                  

Mongoose documents behave similar regular JavaScript objects. We tin get the specials array by writing ryu.specials.

          const ryu = wait Characters.findOne({ name: 'Ryu' }) const specials = ryu.specials console.log(specials)                  
Log of specials.

This specials array is a normal JavaScript array.

          const ryu = expect Characters.findOne({ name: 'Ryu' }) const specials = ryu.specials console.log(Array.isArray(specials)) // true                  

We can utilize the push method to add a new item into specials,

          const ryu = await Characters.findOne({ proper noun: 'Ryu' }) ryu.specials.push({   name: 'Jodan Sokutou Geri',   keys: '↓ ↘ → K' })                  

After updating specials, nosotros run save to save Ryu to the database.

          const ryu = await Characters.findOne({ name: 'Ryu' }) ryu.specials.push({   name: 'Jodan Sokutou Geri',   keys: '↓ ↘ → K' })  const updated = expect ryu.save() console.log(updated)                  
Ryu updated with Jodan Sokutou Geri

Updating a single subdocument

It's even easier to update single subdocuments. You can edit the certificate directly like a normal object.

Let'southward say nosotros desire to modify Ryu's ultimate name from Shinku Hadoken to Dejin Hadoken. What nosotros practise is:

  1. Apply findOne to get Ryu.
  2. Change the proper noun in ultimate
  3. Run save
          const ryu = await Characters.findOne({ name: 'Ryu' }) ryu.ultimate.proper name = 'Dejin Hadoken'  const updated = await ryu.save() console.log(updated)                  
Ryu document with Dejin Hadoken.

If you enjoyed this article, please back up me by sharing this article Twitter or buying me a java 馃槈. If y'all spot a typo, I'd capeesh if you tin can correct information technology on GitHub. Give thanks you lot!

How To Update Child Schema In Moongoose And Save Parent Schema,

Source: https://zellwk.com/blog/mongoose-subdocuments/

Posted by: nelsonvoked1938.blogspot.com

0 Response to "How To Update Child Schema In Moongoose And Save Parent Schema"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel