Add field not in schema with mongoose

24,665

Solution 1

You can add and remove fields in 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 documentations here

Solution 2

You can add new fields in schema User using .add

require('mongoose').model('User').schema.add({fullName: String});

Thanks.-

Share:
24,665

Related videos on Youtube

LuisEgan
Author by

LuisEgan

Updated on July 10, 2021

Comments

  • LuisEgan
    LuisEgan almost 3 years

    I am trying to add a new field to a document, but this isn't working:

    Creating my UserModel prototype:

    model = require("../models/user")
    UserModel.prototype.findOneAndUpdate = function(query, params, cb) {
        model.findOneAndUpdate(query, params, { returnNewDocument: true, new: true }, function(err, data) {
            if (!err) {
                cb(false, data);
            } else {
                cb(err, false);
            }
        });
    };
    

    Then calling it

    userFunc = require("../../model_functions/user")
    
    userFunc.findOneAndUpdate({
        "email.value": userEmail
    }, {
        $set: {"wat":"tf"}
    },
    function (err, updatedUser) {
        //This logs the updated user just fine, but the new field is missing
            console.log(updatedUser);
                      ...
    });
    

    This successfully updates any field as long as it exists, but it won't add any new one.

    • Ashh
      Ashh almost 6 years
      that new field have been added in schema?
    • Jonathan Lonowski
      Jonathan Lonowski almost 6 years
      Is wat defined within the schema for users? Mongoose is designed to enforce the schema, including discarding properties that don't align to it.
    • LuisEgan
      LuisEgan almost 6 years
      No, but that shouldn't be necessary to add it, or at least that's what I thought. It is meant to be a temporary field.
    • LuisEgan
      LuisEgan almost 6 years
      Also, if I do it directly in the mongo console, it works, it adds the new field.
    • Jonathan Lonowski
      Jonathan Lonowski almost 6 years
      @LuisEgan It does matter with Mongoose. The ODM is designed to enforce the schema you've defined, verifying that each property belongs and discarding those that don't. If you want documents to be a blend of schema and schema-less, you can define a property as Mixed type that can then contain any variety of information needed. Otherwise, if you don't want the schema enforced like this, then Mongoose probably isn't right for your use case.
    • LuisEgan
      LuisEgan almost 6 years
      Oh so it's not possible having a temporary field using mongoose.. my solution was adding it to the schema but since it's not going to always be used it seemed like unnecessary code. I'll just it to the schema then. Thanks @JonathanLonowski
  • Ashh
    Ashh almost 6 years
    It is possible... Use { strict: false } to set or unset the new field in mongoose... Read this github.com/Automattic/mongoose/issues/5378
  • Jonathan Lonowski
    Jonathan Lonowski almost 6 years
    @AnthonyWinzlet Forgot about that. Good call. – Relevant documentation.
  • LuisEgan
    LuisEgan almost 6 years
    Ok, but I'd like to add that the first did not work for me, just adding it to findOneAndUpdate() did.
  • Ashh
    Ashh almost 6 years
    It does work if you run the create or insert query... Here main motive is to aware people with option strict and the fact that people can add and remove field if the field does not exists in mongoose schema
  • Tarun
    Tarun about 4 years
    It worked for me. I don't need to compromise on Model strictness.
  • Avani Khabiya
    Avani Khabiya almost 3 years
    For me, the option first i.e. setting the strict to false worked for insert and update both.
  • Avani Khabiya
    Avani Khabiya almost 3 years
    In this case, how to check if the field exists or not in the schema and then add it if not exists?