Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose get not working ( SchemaType#get(fn) )

I was looking at the API docs of mongoose and found the get option. However it seems not to work for me.

This is the Schema with the get option:

var PostSchema = new Schema({
  content: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now,
    get: function (val) {
      return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear() + " " + (val.getHours() + 1) + ":" + (val.getMinutes() + 1) + ":" + (val.getSeconds() + 1);
    }
  }
})

This is where I fetch all the documents:

var Post = App.model('post')
exports.fetchAll = function (req, res, next) {
  Post.find({}).sort({date: 'desc'}).exec(function (err, posts) {
    if (err) { return next(err) }
    res.json(posts)
  })
}

But the results is still the same. On the client side I receive the non formatted string for {{ post.date }}:

2015-10-18T07:56:24.606Z

I can't figure out why the formatted date string doesn't get returned.

like image 917
commonUser Avatar asked Dec 08 '25 22:12

commonUser


1 Answers

You can tell mongoose to use the getters when converting the documents to JSON by adding the getters: true option to the schema. Mongoose makes this an option, since you may or may not want to have different logic when converting the document to an object (keep the raw date object) or to JSON (formatted date string):

var PostSchema = new Schema({
  content: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now,
    get: function (val) {
      return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear() + " " + (val.getHours() + 1) + ":" + (val.getMinutes() + 1) + ":" + (val.getSeconds() + 1);
    }
  }
},
{
    toJSON: {
        getters: true
    }
})
like image 124
Brian Shamblen Avatar answered Dec 10 '25 23:12

Brian Shamblen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!