node.js - 发送带有 id 的 GET 请求的错误请求(ExpressJS)

标签 node.js mongodb express mongoose mean

使用 MEAN.JS。路线:

 app.route('/api/user/cards/:cardId')
   .get(card.read);
 app.param('cardId', card.cardByID);

卡片ID:

exports.cardByID = function (req, res, next, id) {
      Card.findOne({id: id}).exec(function (err, card) {
       if (err) return next(err);
       if (!card) return res.status(404).send({message: 'Карты с таким ID не найдено'});
       req.card = card;
       next();
     });
    };

我曾经使用 mongoose _id 作为参数,但需要使用其他 id(8 位数字)。 如果 id 是 mongoose id 类型(例如 57ceda7ec10c15da7c53515f),它会返回 404 状态,但如果 id 只是一个数字(例如 13241234),它会返回 400 状态。 有什么问题吗?

最佳答案

正如MongoDB所说,作为文档的主键_id生成的默认唯一标识符是一个ObjectId

<小时/>

And it's 12-byte binary value which is often represented as a 24 character hex string.

只要 MongoDB 得到的字符少于 24 个字符,它就不会接受 _id。这就是为什么您会从 MongoDB 端收到一些错误

关于node.js - 发送带有 id 的 GET 请求的错误请求(ExpressJS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39353568/

相关文章:

node.js - 如何进行服务器端获取调用?

node.js - 在 NodeJS 中使用 `import` 时出错

linux - 无法使用 pip 下载 mongo-connector

python - Flask-Restful:通过 POST 请求将列表传递到 MongoDB

node.js - 从 Gruntfile.js 迁移到 gulpfile.js

node.js - 使用 Passport 在 Node JS 中实现基于 cookie 的身份验证

.net - 我应该使用哪个 NoSQL 数据库进行日志记录?

javascript - 简单的游戏循环 Socket.io + Node.js + Express

node.js - Jade/Pug - 附加到类名

javascript - 生成文件的可下载链接并自动启动下载