1
\$\begingroup\$

I'm creating a Mongoose model for a web service. I have a secondary index on facultyId because majority of the reads would want to search by facultyId. I've included some statics on the model in order to make it simple for people to query.

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

mongoose.Promise = global.Promise;

const GAPFApplicationSchema = new Schema({
  facultyId: { type: Number, index: true },
  created: Number, // use UNIX time stamps for all dates
  lastModified: Number,
  status: { type: String, enum: ["SUBMITTED", "BUDGET_ALLOCATED"] },
  attachedDocuments: [
    {
      name: String,
      link: String,
      attachedDate: Number
    }
  ]
});

GAPFApplicationSchema.static("findByFacultyId", function(facultyId, callback) {
  return this.findOne()
    .where("facultyId")
    .equals(facultyId);
});

GAPFApplicationSchema.static("submit", function(gapf, callback) {
  return this.findOneAndUpdate(
    { facultyId: gapf.facultyId },
    gapf,
    { upsert: true }, // create it if doesn't exist
    callback
  );
});

const GAPFApplication = mongoose.model(
  "GAPFApplication",
  GAPFApplicationSchema
);

export { GAPFApplication };

I haven't used Mongoose before, so I was hoping to get some review on the approach taken here. The code is pretty short, so I didn't think there would be much to address.

\$\endgroup\$
1
\$\begingroup\$

You have created a good model overall and I can only suggest you some consideration.

Instead of using, created & lastModified. I would recommend you to use timestamp option in mongoose.

const GAPFApplicationSchema = new Schema({
  facultyId: { type: Number, index: true },
  status: { type: String, enum: ["SUBMITTED", "BUDGET_ALLOCATED"] },
  attachedDocuments: [
    {
      name: String,
      link: String,
      attachedDate: Number
    }
  ]
}, {timestamp: true});

With this you won't need lastModified & created you will get 2 attributes createdAt & updatedAt and they would be handled by mongoose, so you wont have to worry about updating them.

status: { type: String, enum: ["SUBMITTED", "BUDGET_ALLOCATED"] },

you can also improve this piece of code, by changing it to number and create an internal mapping, this would allow mongoDB to search faster, as comparing string is much heavier task, than comparing numbers.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.