过滤特定类型的所有项目(参考文档)

时间:2015-07-31 19:17:11

标签: angularjs mongodb mongoose mean-stack meanjs

我正在尝试查询inventory.products台计算机的所有inventory.product.type。我不知道该怎么做。我已经阅读了文档,并尝试了一些,但似乎:db.inventory.products.find({type: { code: {$in: ['computers'] } } })将是正确的方法,但永远不会收回任何类型的产品。

我在mongo提示符中构建查询的原因是,当我成功时,我可以将其移动到我的服务中。

有什么建议吗?

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);

1 个答案:

答案 0 :(得分:3)

解决方案是在我的服务中创建一个方法,如下所示:

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;
  });
};

这允许我根据需要查询type.code并返回与query

匹配的所有内容