3

let's say I have a field that contains a default value, I want to use this default value only when I save() the data, but I don't want to see the default value if I fetched data that doesn't include the desired field

//ignore any syntax or any other errors
let dataSchema = new mongoose.Schema({
    createdAt: {
        type: Date,
        default: Date.now
    },
    ....
})

let dataSchemaWithoutDefault = new mongoose.Schema({
    createdAt: Date
        ....
})

let dataModelWithoutDefault = mongoose.model("data", dataSchemaWithoutDefault)
let record = dataModelWithoutDefault.save() //createdAt doesn't present

//let's fetch data but with the default value enabled
let dataModel = mongoose.model("data", dataSchema)
dataModel.find().then(data => console.log(data))

//this with console data with default values, but I need a typical copy from the real collection
//[{createaAt:2018-11-12T06:54:50.119Z},...]
Krupesh Kotecha
  • 2,396
  • 3
  • 21
  • 40
xx yy
  • 529
  • 1
  • 7
  • 16
  • Can you be more specific here? Setting `default` alters `insert()` and `update()` statements so that the value is **always** stored. What do you think is different about "reading" here? – Neil Lunn Nov 12 '18 at 07:23
  • you are right, but what if I already inserted some data without default values? I need to get those data without any default values when I fetch them later with dataModel which include default values – xx yy Nov 12 '18 at 07:29
  • Yeah, well your "what if!" actually breaks the rules and conventions of **Schema**, which *"should"* be the reason you are using Mongoose or indeed any ODM type of product. If you just want the "raw data" then that is what MongoDB and the "plain drivers" do right out of the box. Or indeed don't set a "schema". But you cannot have it both ways. – Neil Lunn Nov 12 '18 at 07:32
  • Also [`lean()`](https://mongoosejs.com/docs/api.html#query_Query-lean) would pretty much just return the "raw" document as well. Does not fully describe the behavior in the docs, but it basically "ignores schema". So "missing data" also applies there. – Neil Lunn Nov 12 '18 at 07:34
  • I'm using mongoose for data modeling, but it sometimes a very bad idea to modify old existing data when fetching them, for example I want to check if the field is set in the real collection or not? – xx yy Nov 12 '18 at 07:34

1 Answers1

1

use callback function in save method

   dataModelWithoutDefault.save(function (err, schema) {
    if (err) {
        response.status(500).send(err);
    } else {
        //use your default value
    }
})
Sari Masri
  • 206
  • 1
  • 10
  • this will make me to take care about passing default values to each query, also it will separate schema definition from it's default values, this will make it difficult to maintain – xx yy Nov 12 '18 at 07:26