Add field not in schema with mongoose
Asked Answered
C

4

27

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.

Collinsia answered 19/6, 2018 at 18:28 Comment(6)
that new field have been added in schema?Jerrome
Is wat defined within the schema for users? Mongoose is designed to enforce the schema, including discarding properties that don't align to it.Tool
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.Collinsia
Also, if I do it directly in the mongo console, it works, it adds the new field.Collinsia
@Collinsia 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.Tool
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 @JonathanLonowskiCollinsia
J
37

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

Jerrome answered 19/6, 2018 at 18:55 Comment(4)
Ok, but I'd like to add that the first did not work for me, just adding it to findOneAndUpdate() did.Collinsia
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 schemaJerrome
For me, the option first i.e. setting the strict to false worked for insert and update both.Antiworld
does the strict option also effect the read operation?Wangle
N
12

You can add new fields in schema User using .add

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

Thanks.-

Nothing answered 30/8, 2018 at 3:44 Comment(2)
It worked for me. I don't need to compromise on Model strictness.Verruca
In this case, how to check if the field exists or not in the schema and then add it if not exists?Antiworld
D
1

use {strict:false} when you are creating schema

const testschema = mongoose.Schema({
    name: String,
    id: Number,
    isUsed: {
        type: Boolean,
        default: true
    },
},{strict:false})
Didache answered 7/1, 2023 at 13:34 Comment(0)
C
0

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.

Collinsia answered 19/6, 2018 at 18:49 Comment(2)
It is possible... Use { strict: false } to set or unset the new field in mongoose... Read this github.com/Automattic/mongoose/issues/5378Jerrome
@AnthonyWinzlet Forgot about that. Good call. – Relevant documentation.Tool

© 2022 - 2024 — McMap. All rights reserved.