【问题标题】:Filtering all items of specific type (ref document)过滤特定类型的所有项目(参考文档)
【发布时间】:2015-10-23 13:42:22
【问题描述】:

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

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

有什么建议吗?

库存.产品

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

【问题讨论】:

    标签: angularjs mongodb mongoose mean-stack meanjs


    【解决方案1】:

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

    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 匹配的所有内容

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-06
      • 2015-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-28
      相关资源
      最近更新 更多