0

As you know, MongooseJS has a "default" property available. For instance, if I want a Date property on my object, and I want that date to automatically default to the time at which the record is created, I would define it in the schema as:

var myObject = mongoose.Schema({
  date: {type: Date, default: Date.now}
});

Now, the problem with doing this in CoffeeScript is that default is a reserved keyword in JavaScript, so the CoffeeScript compiler automatically wraps default in double quotes, so this CoffeeScript code:

myObject = mongoose.Schema
    date:
        type: Date
        default: Date.now

is compiled as:

var myObject;
myObject = mongoose.Schema({
    date: {type: Date, "default": Date.now}
});

This results in the default parameter not working as intended. Perhaps I'm missing something but everything I have tried just is not working. I shouldn't need to manually set the date when saving the record, as the default keyword already provides this functionality.

Does anyone know how to get around this?

razorbeard
  • 2,924
  • 1
  • 22
  • 29
  • 2
    Having that key as `"default":` instead of `default:` is just fine and won't stop it from working. Something else is going on here. – JohnnyHK Jan 19 '13 at 16:03
  • Can you point me to something explaining this? I've compiled the CoffeeScript to JS and manually removed the double quotes around the `default` property, and it seems to work. – razorbeard Jan 19 '13 at 16:08
  • 2
    I actually _add_ those quotes to my `default` keys in Mongoose schemas to keep my editor's JS linter happy, so I know it works. More generally, here's an [SO question](http://stackoverflow.com/questions/4348478/what-is-the-difference-between-object-keys-with-quotes-and-without-quotes) about keys with quotes vs. without. There are only a few edge cases where they're different. – JohnnyHK Jan 19 '13 at 16:39

2 Answers2

1

I have to admit I hate CoffeeScript and the like, but you probably might get around this by doing something like this:

var schema = {
   type: Date
};

schema["default"] = Date.now;

myObject = mongoose.Schema(schema);
bevacqua
  • 47,502
  • 56
  • 171
  • 285
  • This seems interesting and it works, but I'm rather inquisitive as to JohnnyK's comment on my question - waiting for further input before I accept an answer. – razorbeard Jan 19 '13 at 16:09
0

So, the solution to my problem was rather simple, and a rookie mistake: I forgot to specify the Date property to return in myObject.find()...

razorbeard
  • 2,924
  • 1
  • 22
  • 29