Express/Mongoose Router:“在路径”_id“处,对于值”undefined“,强制转换为 Obje
Express/Mongoose Router: 'Cast to ObjectId failed for value "undefined" at path "_id"'
我在Express中有一个简单的API,允许用户将帖子标题"发布"和"删除"到MongoDB数据库中。出于某种原因,当我添加帖子标题,然后"删除"它时,我得到"在路径"_id"处为值"未定义"的 Cast to ObjectId 失败。
创建帖子后调用"删除"时,似乎不存在"_id"。但是,当我刷新页面,然后单击"删除"时,它会很好地获得"_id"并删除该条目。
我在路由中是否做错了什么,无法生成"_id"并能够立即从帖子中拉出?
module.exports = function(router) {
var Post = require('../models/post.js');
// middleware for the api requests
router.use(function(req, res, next) {
// do logging
console.log('something is happening.');
next(); // make sure we go to our next route and don't stop here
});
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
// all routes here
// routes that end in /posts
router.route('/posts')
// create a Post (accessed at POST http://localhost:7777/api/posts)
.post(function(req, res) {
var post = new Post();
post.postTitle = req.body.postTitle; // set the post name (comes from request)
console.log(post._id);
// save post and check for errors
post.save(function(err) {
if (err)
return res.status(300).send(err);
res.json({ message: 'post created!' });
});
})
// get all Posts (accessed at GET http://localhost:7777/api/posts)
.get(function(req, res) {
Post.find(function(err, posts) {
if (err)
return res.send(err);
res.json(posts);
});
});
// routes that end in /posts for specific id
router.route('/posts/:post_id')
// get the post with that id
.get(function(req, res) {
Post.findById(req.params.post_id, function(err, post) {
if (err)
return res.send(err);
res.json(post);
});
})
// update the post with that id
.put(function(req, res) {
Post.findById(req.params.post_id, function(err, post) {
if (err)
return res.send(err);
post.postTitle = req.body.postTitle;
// save the post
post.save(function(err) {
if (err)
return res.send(err);
res.json({ message: 'post updated!' });
});
});
})
// deletes the post with that id
.delete(function(req, res) {
Post.findOne({
_id:req.params.post_id
}).remove(function(x){
console.log("removed: ", x);
});
})
.patch(function(req, res) {
Post.findOne({
_id: req.body._id
}, function(err, doc) {
for (var key in req.body) {
dock[key] = req.body[key];
}
doc.save();
res.status(200).send();
});
});
}
/
function addPostItem(post){
posts.push(post);
triggerListeners();
helper.post("/api/posts", post);
}
function deletePost(post) {
var index = posts.indexOf(post);
console.log(post);
posts.splice(index, 1);
triggerListeners();
helper.del('api/posts/' + post._id);
}
/
var $ = require('jquery');
module.exports = {
get: function(url) {
return new Promise(function(success, error) {
$.ajax({
url: url,
dataType: 'json',
success: success,
error: error
});
});
},
post: function(url, data) {
return new Promise(function(success, error) {
$.ajax({
url: url,
type: 'POST',
data: data,
success: success,
error: error
});
});
},
patch: function(url, data) {
return new Promise(function(success, error) {
$.ajax({
url: url,
type: 'PATCH',
data: data,
success: success,
error: error
});
});
},
del: function(url) {
return new Promise(function(success, error) {
$.ajax({
url: url,
type: 'DELETE',
success: success,
error: error
});
});
}
};
在 addPostItem 中,在进行 POST 调用之前,将帖子添加到客户端模型列表中。您推送到 posts 数组上的新创建的帖子将没有_id,因为它是在服务器上生成的并且不会返回。当您向服务器传递一个未定义的_id以发送此新帖子时,任何针对它的 api 调用都将失败并出现相同的错误。
当您刷新页面并调用 get 函数时,您的所有帖子都有一个_id,因此一切正常。
要遵循的典型模式是在创建帖子时将创建的 id(或整个帖子)返回给客户端,然后将其添加到您的 items 数组中(如下所示):
function addPostItem(post){
triggerListeners();
helper.post("/api/posts", post, function(res){
posts.push(res.data);
});
}
您还需要重写 POST 请求以返回创建的实体:
post.save(function(err) {
if (err)
return res.status(300).send(err, o);
res.json(o);
});
一种变体是只返回._id。另一种方法是在客户端创建id,但是这样你就失去了本机mongo ObjectIds的一些优势。
相关文章:
- 如何将返回的值应用于多个不同位置的多个选择器
- 如何查找值是否存在于二叉树中
- jQuery可以't获取data-*属性值,返回undefined
- 使用在函数外部声明的变量的 Javascript 返回值 + undefined
- 如何隐藏&使用jQuery禁用依赖于另一个字段值的字段
- 如何使AngularJS控制器依赖于通过ajax加载在rootScope上的值
- 逻辑(JSint友好)等效于while循环中的此赋值
- 使用 HTML 和 JavaScript 从表单访问值时返回 undefined
- 如何使用 jquery 检查该值是否存在于带有标签的 select2 下拉列表中:true
- 将 var 的值应用于加载页面中的另一个变量
- 选择数据属性日期值早于当前服务器日期的元素
- Chrome没有正确地将值应用于正在被“刷新”的输入;观看”;
- 如果我们设置undefined的值会发生什么
- 如何捕获相对于常数值的下一个值
- foreach 循环和返回值 undefined
- Express/Mongoose Router:“在路径”_id“处,对于值”undefined“,强制转换为 Obje
- 值undefined(表达式console.time的结果)不是对象
- JQuery: ajax请求返回值"undefined"在同一个函数内
- 角度指令不应用于值的更改
- 未定义的指令值'undefined'在View组件上(angular 2.0)