Node.js 使用express按参考字段筛选moongose结果
我需要按类别id筛选集合的产品,类别id是一个参考字段 product.jsNode.js 使用express按参考字段筛选moongose结果,node.js,express,mongoose,Node.js,Express,Mongoose,我需要按类别id筛选集合的产品,类别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,
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)
您必须在路线中执行以下操作:
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);
}
});
});
这只是一个基本的例子。由于您使用的是node restful,您可能需要调整代码,但这里的主要思想是您需要mongoose模块使用
const mongoose=require('mongoose')
然后将类别查询参数传递给它,以便使用以下命令将字符串转换为objectID:
mongoose.Types.ObjectID(此处为您的类别参数)
您可以在任意位置执行此操作,无论是在your routes.js还是在您的express.js中,只要有要转换的字符串:)
希望有帮助:)。您可以使用猫鼬类型<代码>mongoose.Types.ObjectId('req.query.category')代码>@SunnyGohil,我在哪里可以这么做?在express中还是在product.js中?如果你有一个例子,我很感激。请看下面的答案。首先,谢谢你的回复@SunnyGohil。我将路由放在routes.js中,如果使用空对象传递find(),我将获得所有产品。但当我尝试按类别筛选时,我总是得到一个空返回。我忘了告诉你,按名称筛选也可以,只是类别不行。你的“CategoryProduct”模式是什么样子的?你能把代码也包括进去吗?。您要传递的类别id肯定存在于数据库中,对吗?当你传递身份证时,没有输入错误或其他任何东西?补充!是的,ID是存在的,我尝试了更多的ID。不,我直接从退货中复制ID,然后粘贴。