gre*_*emo 102 mongoose mongodb
当发送请求/customers/41224d776a326fb40f000001和文件_id 41224d776a326fb40f000001不存在时,doc是null,我正在返回404:
Controller.prototype.show = function(id, res) {
this.model.findById(id, function(err, doc) {
if (err) {
throw err;
}
if (!doc) {
res.send(404);
}
return res.send(doc);
});
};
Run Code Online (Sandbox Code Playgroud)
但是,如果_id不匹配Mongoose所期望的"格式"(我想),例如GET /customers/foo返回一个奇怪的错误:
CastError:对于路径"_id"处的值"foo",转换为ObjectId失败.
那么这个错误是什么?
Joh*_*yHK 163
Mongoose的findById方法将id参数转换为模型_id字段的类型,以便它可以正确查询匹配的doc.这是一个ObjectId但"foo"不是有效的ObjectId,因此转换失败.
这不会发生41224d776a326fb40f000001因为该字符串是有效的ObjectId.
解决此问题的一种方法是在findById调用之前添加一个检查,以查看是否id是有效的ObjectId,如下所示:
if (id.match(/^[0-9a-fA-F]{24}$/)) {
// Yes, it's a valid ObjectId, proceed with `findById` call.
}
Run Code Online (Sandbox Code Playgroud)
xpe*_*int 38
使用现有函数检查ObjectID.
var mongoose = require('mongoose');
mongoose.Types.ObjectId.isValid('your id here');
Run Code Online (Sandbox Code Playgroud)
Har*_*rma 27
如果您有两条不同的路线,如下所示,这可能是路线不匹配的情况
router.route("/order/me") //should come before the route which has been passed with params
router.route("/order/:id")
Run Code Online (Sandbox Code Playgroud)
那么你必须小心地将使用参数的路线放在对我有用的常规路线之后
Rya*_*gel 16
我不得不将我的路线移动到捕获路线参数的其他路线之上:
// require express and express router
const express = require("express");
const router = express.Router();
// move this `/post/like` route on top
router.put("/post/like", requireSignin, like);
// keep the route with route parameter `/:postId` below regular routes
router.get("/post/:postId", singlePost);
Run Code Online (Sandbox Code Playgroud)
Blo*_*gic 12
当您将无效的 id 传递给 mongoose 时,就会发生这种情况。isValid所以在继续之前首先使用 mongoose函数检查它
import mongoose from "mongoose";
// add this inside your route
if( !mongoose.Types.ObjectId.isValid(id) ) return false;
Run Code Online (Sandbox Code Playgroud)
gus*_*nke 11
你在解析那个字符串ObjectId吗?
在我的应用程序中,我所做的是:
ObjectId.fromString( myObjectIdString );
Run Code Online (Sandbox Code Playgroud)
截至2019年11月19日
您可以isValidObjectId(id)从 mongoose 版本 5.7.12 开始使用
https://mongoosejs.com/docs/api/mongoose.html#mongoose_Mongoose-isValidObjectId
小智 5
if(mongoose.Types.ObjectId.isValid(userId.id)) {
User.findById(userId.id,function (err, doc) {
if(err) {
reject(err);
} else if(doc) {
resolve({success:true,data:doc});
} else {
reject({success:false,data:"no data exist for this id"})
}
});
} else {
reject({success:"false",data:"Please provide correct id"});
}
Run Code Online (Sandbox Code Playgroud)
最好是检查有效性
| 归档时间: |
|
| 查看次数: |
140240 次 |
| 最近记录: |