LuisEgan
LuisEgan

Reputation: 1024

Add field not in schema with mongoose

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.

Upvotes: 27

Views: 36348

Answers (4)

Gouranga Satapathy
Gouranga Satapathy

Reputation: 432

use {strict:false} when you are creating schema

const testschema = mongoose.Schema({
    name: String,
    id: Number,
    isUsed: {
        type: Boolean,
        default: true
    },
},{strict:false})

Upvotes: 1

Ashh
Ashh

Reputation: 46451

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

Upvotes: 37

Alvaro
Alvaro

Reputation: 651

You can add new fields in schema User using .add

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

Thanks.-

Upvotes: 12

LuisEgan
LuisEgan

Reputation: 1024

Quoting JonathanLonowski

The ODM is designed to enforce the schema you've defined, verifying that each property belongs and discarding those that don't.

So in order to update fields using mongoose the field must exist in the model's schema.

Upvotes: 0

Related Questions