CastError:在猫鼬模型中,路径“ _id”的值“ findByName”的对象转换为ObjectId失败

时间:2018-11-30 11:15:55

标签: node.js mongodb mongoose

我遇到错误了

  

CastError:在路径上由于值“ findByName”而强制转换为ObjectId   型号“产品”的“ _id”       在新的CastError(/Users/me/projects/nodejs/node_modules/mongoose/lib/error/cast.js:29:11)       在ObjectId.cast(/Users/me/projects/nodejs/node_modules/mongoose/lib/schema/objectid.js:156:13)

使用Nodejs编写的API

数据库:mongoDB

控制器:

exports.product_details_by_name = function (req, res) {
    Product.findByProductName(req.params.name, function (err, product) {
        if (err){console.log(err); return next(err);}
        res.send(product);
    })
};

路由器

router.get('/test', product_controller.test);
router.post('/create', product_controller.product_create);
router.get('/:id', product_controller.product_details);
router.put('/:id/update', product_controller.product_update);
router.delete('/:id/delete', product_controller.product_delete);
router.get('/findByName', product_controller.product_details_by_name); // two get methods?

型号:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let ProductSchema = new Schema({
    name: {type: String, required: true, max: 100},
    price: {type: Number, required: true},
});

ProductSchema.findByProductName =  function(nam) { // is it right to do?
console.log("name"+nam);
  return this.find({ "name":  nam  });
};
// Export the model
module.exports = mongoose.model('Product', ProductSchema);

我正在接到邮递员的电话:

URL: localhost:8080 / products / findByName

请求正文:

  {name: "name2"}

js

1 个答案:

答案 0 :(得分:1)

您忘记在模型的findbyProductName函数中添加回调参数。

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let ProductSchema = new Schema({
  name: {type: String, required: true, max: 100},
  price: {type: Number, required: true},
});

// Export the model
let Product = module.exports = mongoose.model('Product', ProductSchema);

exports.findByProductName =  function(nam, callback) { 
  console.log("name"+nam);
  Product.find({ "name":  nam  }).exec(callback);
};