使用express通过参考字段过滤moongose结果

时间:2018-05-22 14:11:43

标签: node.js express mongoose

我需要按类别ID过滤集合的产品,这是一个参考字段。

product.js

const restful = require('node-restful')
const mongoose = restful.mongoose

const productSchema = new mongoose.Schema({
  name: { type: String, required: true },
  category: {type: mongoose.Schema.Types.ObjectId, ref: 'CategoryProduct'}
})

productSchema.pre('find', function () {
  this.find().populate('category')
})

module.exports = restful.model('product', productSchema)

routes.js

const express = require('express')
const auth = require('./auth')
module.exports = function (server) {
  const protectedApi = express.Router()
  server.use('/api', protectedApi)
  const Product = require('../api/product/productService')
  Product.register(protectedApi, '/products')
}

如果我在邮递员http://localhost:3003/api/products/?name__regex=/test/i上运行此邮件,我可以获得包含' test'在名字上。

因此,我尝试按特定类别获取所有产品,http://localhost:3003/api/products/?category=5af3ac4372edc6000468d766。 但由于类别是objectID,我收到此错误:

{
    "message": "Cast to ObjectId failed for value \"5\" at path \"category\" for model \"SimpleProduct\"",
    "name": "CastError",
    "stringValue": "\"5\"",
    "kind": "ObjectId",
    "value": 5,
    "path": "category"
}

如何按类别过滤产品?我不知道如何正确处理这个参数并传递给mongoose

这是我的CategoryProduct.js文件

const restful = require('node-restful')

const mongoose = restful.mongoose

const categorySchema = new mongoose.Schema({
  name: {type: String, required: 'O campo Categoria é obrigatório'},
  status: {type: Number, required: true},
  updated_at: {type: Date}
})

module.exports = restful.model('CategoryProduct', categorySchema)

1 个答案:

答案 0 :(得分:0)

您必须在路线中执行以下操作:

const mongoose = require('mongoose');
router.get('/', (req, res, next) => {
   const category = req.query.category; // assign the query param for use

   // mongoose query now
   Product.find({category: mongoose.Types.ObjectId(category)}, (err, result) => {
      if (err) {console.log(err)};
      if (result) {
         res.json(result);
      }
   });
});

这只是一个基本的例子。由于您使用节点restful,您可能需要调整代码,但这里的主要想法是您需要使用mongoose模块

const mongoose = require('mongoose')

然后将类别查询参数传递给它,使用:

将字符串转换为objectID

mongoose.Types.ObjectID(YOUR_CATEGORY_PARAM_HERE)

你可以在你的routes.js或express.js中的任何地方执行此操作,只需拥有要转换的字符串:)

希望有所帮助:)。