我需要过滤产品的集合,按类别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,我可以得到所有的产品,其中包含‘测试’的名称。
所以我试着用一个特定的类别来获得所有的产品,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"
}如何按类别过滤产品?我不知道如何正确对待这个参数并传递给猫鼬。
这是我的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)发布于 2018-05-23 09:47:59
你必须在你的路线上做以下几件事:
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中,只需使用您想要转换的字符串:)
希望这有帮助:)。
https://stackoverflow.com/questions/50469884
复制相似问题