首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用express对参考场滤波驼鹿结果

用express对参考场滤波驼鹿结果
EN

Stack Overflow用户
提问于 2018-05-22 14:11:43
回答 1查看 147关注 0票数 0

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

product.js

代码语言:javascript
复制
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

代码语言:javascript
复制
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,我可以得到所有的产品,其中包含‘测试’的名称。

所以我试着用一个特定的类别来获得所有的产品,http://localhost:3003/api/products/?category=5af3ac4372edc6000468d766。但是,由于类别是objectID,我收到以下错误:

代码语言:javascript
复制
{
    "message": "Cast to ObjectId failed for value \"5\" at path \"category\" for model \"SimpleProduct\"",
    "name": "CastError",
    "stringValue": "\"5\"",
    "kind": "ObjectId",
    "value": 5,
    "path": "category"
}

如何按类别过滤产品?我不知道如何正确对待这个参数并传递给猫鼬。

这是我的CategoryProduct.js文件

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-23 09:47:59

你必须在你的路线上做以下几件事:

代码语言:javascript
复制
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,所以您可能需要调整代码,但是这里的主要思想是您需要使用

const mongoose = require('mongoose')

然后将类别查询param传递给它,以便使用以下方法将字符串转换为objectID:

mongoose.Types.ObjectID(YOUR_CATEGORY_PARAM_HERE)

您可以在任何地方,无论是在您的routes.js中还是在您的express.js中,只需使用您想要转换的字符串:)

希望这有帮助:)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50469884

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档