2

So I have a problem trying to work with mongodb. Firstly, I created a mongoose model like below which stores name.

const mongoose = require("mongoose");

const schema = new mongoose.Schema({
  name: {
    type: String
  },
 });
 
 mongoose.model("schema", schema);

And I posted a name. It looks like this in my mongodb compass.

{
  "_id": {
    "$oid": "628e0b35062e0d2e7fde17dc"
  },
  "name": "Bob",
}

Now I also want their age so I updated the model to this.

const mongoose = require("mongoose");

const schema = new mongoose.Schema({
  name: {
    type: String
  },
  age: {
    type: Number,
    default: 0
  }
 });
 
 mongoose.model("schema", schema);

The problem
The previous saved data at db doesnt have age property on it. I want previous registered name's age to be default to 0. New data will have the age property to them but not the previous data.

FatFatty
  • 76
  • 1
  • 13
  • 1
    Since, your code is not running for the old data, they won't automatically get age key. Two solutions: 1st -> use a update command to find all data without age key and add add age with value 0. 2nd -> Use mongoose virtuals to add age key in your schema, this will add key to your mongoose response data without having to update mongo data (also, you never get age key in your actual db data). https://mongoosejs.com/docs/guide.html#virtuals – gyan roy May 28 '22 at 06:39

0 Answers0