Monday, 29 May 2017

Mongoose Unique Date (w/o time) Per Document

I'm working on incorporating some user analytics data manually into an app, and I need to ensure that data is only captured once per guid per day. That is, I need to ensure that for a given guid, a new document/entry is only created if one has not been already created on that DATE.

Approaches (not optimal, IMO) that I can think of:

  1. I could manually do a query each time a request comes in. But this is expensive and I'm concerned that approach may impact performance.
  2. I could have it ensure unique createdAt timestamp, but that's a Date+Time format, and would NOT limit entries to one per day (rather one per millisecond or something).
  3. Mongoose seems to have built-in timestamp capabilities, but I have yet to find a simple baked-in solution in Mongoose or Mongo for ensuring uniqueness on date-only.
  4. I can use an aggregator before doing the save, but this is a lot of overhead - requiring a query using $lt & $gt, then after that result, possibly saving the new entry. That's two database interactions per request. That's the closest answer I've found on StackOverflow.
  5. I could create a separate field in the Schema that is Date-only (no time), but that seems a little redundant, since I already have a createdAt timestamp.

Hopefully there's a cleaner & more performant approach for ensuring the one unique guid per Date...

Oh, and the schema currently looks like this (note: timestamps: true creates the createdAt & updatedAt timestamps in the DB and auto-populates them with ISO dates):

var Schema = new Schema({
    guid:             { type: String, required: true },
    targetCategory:   { type: String, required: true },  
    targetIdentifier: { type: String, required: true },  
    targetType:       { type: String, default:  null }, 
    interactorUserId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  },
  { timestamps: true });

Thanks SO!



via cjn

No comments:

Post a Comment