1

I have a react application that performs CRUD operations on data stored in mongodb in the cloud.mongodb.com.

The schema of the data in my react looks like this:

const restaurantSchema = new Schema({
    "uuid": {
        "type": "string"
      },
      "name": {
        "type": "string"
      },
      "city": {
        "type": "string"
      }
}, {timestamps: true});

I would like to add a new field called "preference" of type number.

My questions are:

  1. How do I add this new field of "preference"?
  2. Can I give it a default value of say 1 when I add this new field? (There are 900 entries in the mongodb.)?
  3. Can I give the "preference" value based on the order of the "name" field in ascending order?

thanks.

qed59
  • 51
  • 7
  • Found the answer in this post: https://stackoverflow.com/questions/7714216/add-new-field-to-every-document-in-a-mongodb-collection – qed59 Dec 13 '22 at 22:48

1 Answers1

0

You can add and remove fields in the schema using option { strict: false }

option: strict

The strict option, (enabled by default), ensures that values passed to our model constructor that were not specified in our schema do not get saved to the db.

var thingSchema = new Schema({..}, { strict: false });

And also you can do this in update query as well

Model.findOneAndUpdate(
  query,  //filter
  update, //data to update
  { //options
    returnNewDocument: true,
    new: true,
    strict: false
  }
)

You can check the documentation here

  • Hi Sagar, I "want" to add the new field to the mongodb schema, so the data can look something like this:[ { uuid: 'some id here', name: 'restaurant name 1', city: 'some city1 here', preference: 1 }, { uuid: 'some id here2', name: 'St Andrews Hotel Fitzroy', city: 'some city2 here', preference: 2 } ] – qed59 Dec 13 '22 at 06:55