node.js - 如果未找到 ID,Mongoose 更新文档或插入新文档(Express REST API)

标签 node.js mongodb rest express mongoose

我已经设置了 Express REST Api,并希望实现一项任务来检查某个对象 ID 是否存在。

如果该 ID 存在于 Mongo 数据库中,我想使用 Put 请求更新此文档。这部分已经在我的代码中运行。

如果数据库中尚不存在该 ID,我想创建一个新文档。为此,我尝试将“upsert”选项设置为 true,但是如果我现在向一个 ID 发出 put 请求,该 ID 不在我的数据库中,但它会返回错误:

throw er; // Unhandled 'error' event
  ^
CastError: Cast to ObjectId failed for value "34455ab67" at path "_id" for model "event"

这是我的事件模型代码:

var mongoose = require('mongoose');

var eventSchema = mongoose.Schema({
   name: {
       type: String,
       required: true
   }
});
var Events = module.exports = mongoose.model('event', eventSchema, 'event');

module.exports.updateEvent = function (id, event, options, callback) {
   var query = {_id : id};
   var update = {
       name: event.name,
   };
   Events.findOneAndUpdate(query, update, options, callback);
};

这是 REST API 调用

app.put('/api/event/:_id', function(req, res) {           
   var id = req.params._id;
   var event = req.body;
   var options = {
       upsert: true,
       new: true,
       setDefaultsOnInsert: true
   };
   Events.updateEvent(id, event, options, function(err, event){
       if(err){
           trow err;
       }
       res.json(event);
   })
});

任何帮助将不胜感激!

最佳答案

发生此错误的原因是您定义的事件架构没有“_id”,因此“_id”属性的类型默认变为“ObjectId”,然后当您尝试使用此值“34455ab67”发送“_id”时,mongoose 方法尝试将其转换为“ObjectId”类型,但它是无效字符串。所以你应该执行以下操作:

  1. 发送“_id”属性的有效字符串值。
  2. 先验证输入字符串,然后再将其转换为“ObjectId”。
  3. 如果输入字符串有效,则将其转换为“ObjectId”,然后在中使用它 Mongoose 查询。

检查以下示例:

var mongoose = require('mongoose');
//inputId is the input string passed from the front end
if (inputId.match(/^[0-9a-fA-F]{24}$/)) {
  // it's a valid string to be converted to "ObjectId"
  var id = mongoose.Types.ObjectId(inputId);
  //then use this id in your mongoose queries.
} else {
  //Not valid     
}

或者您可以使用“String”类型定义“_id”来简化此过程,但这取决于您的需求。

关于node.js - 如果未找到 ID,Mongoose 更新文档或插入新文档(Express REST API),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44728768/

相关文章:

javascript - 设置 mongo 的更好方法是什么?

mongodb - 属性错误: 'Bottle' object has no attribute 'template'

java - 将MongoDB查询结果保存到Java中的不同变量中

java - 如何区分项目的问题,同时检索所有项目的所有问题?

http - 设计合适的 REST URI

javascript - 是否可以通过 URL 从 NPM 下载并安装 JS 文件(不是 NPM 包)?

mysql - 从nodejs调用存储过程返回错误

mongodb - MongoDB 是否适合某些用例?

rest - 如何设置OAuth1.0a的授权 header

javascript - 如何在 node.js 中实现 readUInt16BE 函数