简体   繁体   中英

How to modify added dynamically document fields in MongoDB

I'm using MEAN.io for a project. In MEAN.io, the package for managing the users is located in node_modules so it mustn't be modified. The MongoDB model for users is located there so if I want to add new fields I have to do it by using schema.add method from my own custom created packages:

user.schema.add({
    field1: [],
    deleted_at: {
      type: Date,
      default: null
    },
    banned_at: {
      type: Date,
      default: null
    },
    created_at: {
      type: Date,
      default: new Date()
    },
    field2: {
      type: Number,
      default: 0
    },
    field3: {
      type: Number,
      default: 0
    },
    field4: {
      type: Number,
      default: 0
    }
});

Everything seems to work pretty well, but when I've tried to modify the deleted_at field doing something like this:

user.deleted_at = new Date();
console.log(user);

User object doesn't show any trace of the deleted_at field. It doesn't just change anything.

So the question is how can I modify a field added dynamically?

Thanks in advance!

Problem is that by design schemas are compiled into models and cannot be edited dynamically. This thread ( here ) contains the information about mongoose but the same is true for other methods of adding field dynamically to the database schema.

You should use mixed types if you are not sure about your schema. Go through @vkarpov15 comments for other options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM