Monday 12 June 2017

Mongoose Virtual field with async getter

I have a item model where it a virtual field to refer stock badges.

'use strict';

const mongoose = require('mongoose');
const mongooseHidden = require('mongoose-hidden')();
const Badge = mongoose.model('Badge');

const validateProperty = function(property) {
  return (property.length);
};

const Schema = mongoose.Schema;

const ItemSchema = new Schema({
  itemCode: {
    type: Number,
    index: {
      unique: true,
      sparse: true // For this to work on a previously indexed field, the index must be dropped & the application restarted.
    },
    required: true
  },
  itemName: {
    type: String,
    uppercase: true,
    trim: true
  },
  barcode: {
    type: String,
    trim: true
  },
  category: {
    type: Schema.Types.ObjectId,
    ref: 'Category'
  },
  subCategory: {
    type: Schema.Types.ObjectId,
    ref: 'SubCategory'
  },
  updated: {
    type: Date
  },
  created: {
    type: Date,
    default: Date.now
  },
  status: {
    type: String,
    enum: [
      'active', 'inactive', 'removed'
    ],
    default: 'active'
  }
}, {id: false});

ItemSchema.virtual('badges').get(function() {
  return this.getAvailableBadges();
});

ItemSchema.methods.getAvailableBadges = function() {
  Badge.find({
    item: this._id
  }, (err, badges) => {
    if (badges) {
      return badges;
    } else {
      return [];
    }
  });
};

ItemSchema.set('toJSON', {virtuals: true});
ItemSchema.set('toObject', {virtuals: true});

ItemSchema.plugin(mongooseHidden, {
  hidden: {
    _id: false,
    __v: true
  }
});

mongoose.model('Item', ItemSchema);

And batch model as below

'use strict';

const mongoose = require('mongoose');
const mongooseHidden = require('mongoose-hidden')();

const validateProperty = function(property) {
  return (property.length);
};

const Schema = mongoose.Schema;

const BadgeSchema = new Schema({
  item: {
    type: Schema.Types.ObjectId,
    ref: 'Item'
  },
  qty: {
    type: Number,
    validate: [validateProperty, 'Please enter Quantity !']
  },
  purchasingPrice: {
    type: Number,
    validate: [validateProperty, 'Please enter purchasingPrice !']
  },
  sellingPrice: {
    type: Number,
    validate: [validateProperty, 'Please enter sellingPrice !']
  },
  updated: {
    type: Date
  },
  created: {
    type: Date,
    default: Date.now
  },
  status: {
    type: String,
    enum: [
      'active', 'inactive', 'removed'
    ],
    default: 'active'
  }
});

BadgeSchema.plugin(mongooseHidden, {
  hidden: {
    _id: false,
    __v: true
  }
});

mongoose.model('Badge', BadgeSchema);

Item's badge virtual field doesn't got populated.

How are we going to work with async getter method

I have put some console log statements and found that getAvailableBadges is getting data.



via user2473015

No comments:

Post a Comment