Search code examples
angularjsmongodbmongoosemean-stackmeanjs

Filtering all items of specific type (ref document)


I am trying to query all inventory.products that are of inventory.product.type computers. I am not sure how to do this. I have read the documentation and have tried a few but it seems like: db.inventory.products.find({type: { code: {$in: ['computers'] } } }) would be the proper way but never get back any products of the type.

The reason I am building my query in mongo prompt is so I can move it to my service when I have success.

Any advice?

Inventory.Product

'use strict';

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ProductSchema = new Schema({
  name: {
    type: String,
    required: 'Name is required'
  },
  type: {
    type: Schema.ObjectId,
    ref: 'Inventory.Product.Type',
    required: 'Product type is required'
  },
});

mongoose.model('Inventory.Product', ProductSchema);

Inventory.Product.Type

'use strict';

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ProductTypeSchema = new Schema({
  code: {
    type: String,
    trim: true
  },
  name: {
    type: String,
    required: 'Please enter name',
    trim: true
  },
});

mongoose.model('Inventory.Product.Type', ProductTypeSchema);

Solution

  • The solution was to create a method in my service like so:

    service.autoCompleteType = function(query) {
      var productList = null;
      var products = [];
    
      return Product
        .find()
        .populate('type')
        .exec()
        .then(function(products){
          productList = products;
        })
        .then(function(quantities){
          for (var i in productList) {
            if (productList[i].type.code === query) {
              products.push(productList[i]);
            }
          }
        return products;
      });
    };
    

    This allowed me to query type.code as required and returned everything matching query