Advertisement
nubilfi

Socket.io and mongoose virtual

May 14th, 2017
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // app/models/feed.js
  2.  
  3. const FeedSchema = new Schema(
  4.   {
  5.     user: { type: Schema.ObjectId, ref: 'User' },
  6.     toolkit: { type: Schema.ObjectId, ref: 'Item' },
  7.     notes: { type: String, required: true },
  8.     trx_date: { type: Date }
  9.   }
  10. );
  11.  
  12. FeedSchema.set('toObject', { getters: true  });
  13.  
  14. // Virtual date_formatted
  15. FeedSchema
  16.   .virtual('trx_date_formatted')
  17.   .get(function () {
  18.     return this.trx_date ? moment(this.trx_date).format('YYYY-MM-DD') : '';
  19.   });
  20.  
  21. module.exports = mongoose.model('Feed', FeedSchema);
  22. ==============================================================================================================
  23.  
  24. // routes/home.js
  25. // == Open socket.io connection ==
  26.   io.sockets.on('connection', (socket) => {
  27.     async.parallel({
  28.       toolkits: function (callback) {
  29.         Toolkit
  30.           .find({})
  31.           .sort({ updatedAt: -1, createdAt: -1})
  32.           .select('item_name stock')
  33.           .exec(callback);
  34.       },
  35.  
  36.       feeds: function (callback) {
  37.         Feed
  38.           .find({})
  39.           .sort({ trx_date: -1})
  40.           .populate('user')
  41.           .populate('toolkit')
  42.           .exec(callback);
  43.       }
  44.     }, function (err, results) {
  45.       if (err) {
  46.         throw err;
  47.       }
  48.  
  49.       connections.push(socket);
  50.       console.log('Connected: %s sockets connected', connections.length);
  51.  
  52.       // disconnect
  53.       socket.on('disconnect', (data) => {
  54.         connections.splice(connections.indexOf(socket), 1);
  55.         console.log('Disconnected: %s sockets connected', connections.length);
  56.       });
  57.  
  58.       console.log(results.feeds);     // i can see "trx_date_formatted" virtual here
  59.  
  60.       // show the latest toolkit items and feeds
  61.       io.sockets.emit('show items', { item: results.toolkits, feed: results.feeds });
  62.     });
  63. ==============================================================================================================
  64.  
  65. // views/index.hbs
  66. <script src="/socket.io/socket.io.js" type="text/javascript"></script>
  67. <script>
  68.   'use strict';
  69.  
  70.   var socket = io();
  71.   socket.on('show items', function (data) {
  72.     var toolkitItem = data.item;
  73.     var feedItem = data.feed;
  74.  
  75.     console.log(feedItem);      // i can't see trx_date_formatted here
  76.     ...
  77. </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement