jmfbot
jmfbot

Reputation: 189

Can a mongoose document value be a function?

For the sake of argument, let's take this schema:

const ImaginarySchema = new Schema ({
    Name: String,
    Age: Number,
    Weight: Number, 
    Value: Number, 
    });

In this Schema, the way value is calculated is represented by the following function:

function calculateValue(age, weight) {
    value = Age*Weight; 
};

Given that everyday the age increases by one, this value is of course regularly changing and therefore needs to be calculated with a function automatically.

What is the best way to implement this and where should it be placed in the application?


My attempts:


Firstly, I wanted to try the following syntax, but according to the mongoDB docs it is not advisable to store application logic on the server so saving this function in server.js doesn't seem to be the best idea, and that is assuming that this kind of syntax is even possible.

const ImaginarySchema = new Schema ({
    Name: String,
    AgeinDays: Number,
    Weight: Number, 
    Value: calculateValue(), 
    });

Secondly I was looking at something like below but again I was unclear at whether this should be in the model file, and if it is in the model file, then how could this be run regularly.

.pre('save'), function(next){
function calculateValue(age, weight) {
   value = Age*Weight; 
 next(); 
 };

Thanks in advance for any help.

Upvotes: 1

Views: 922

Answers (2)

ancasen
ancasen

Reputation: 59

According to the mongoose SchemaTypes, a document cannot be a function. Valid types include:

  • String
  • Number
  • Date
  • Buffer
  • Boolean
  • Mixed
  • ObjectId
  • Array
  • Decimal128
  • Map

Upvotes: 0

dropbeardan
dropbeardan

Reputation: 1160

Perhaps you are searching for the elusive Mongoose statics:

https://mongoosejs.com/docs/guide.html#statics

Statics create an artificial method that resolves to what you would like it to be.

If that is not what you are searching for, look below it, there are Query Helpers that might suit your needs.

If that is still not what you are searching for, look below it, there are Virtuals that I think most closely matches your description.


Bar the above, I would not recommend you go about updating your data source (database) to store dynamic values given the same static inputs. I would recommend you have a model layer (that defines the schema and the statics / helpers associated with the schema) and use that instead to calculate your values.

Upvotes: 1

Related Questions