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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Mar 20, 2018 at 15:07
\$\endgroup\$

1 Answer 1

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.

answered Apr 10, 2018 at 12:02
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.