Express/Mongoose Router: 'Cast to ObjectId failed for value “undefined” at path “_id”'

旧时模样 提交于 2019-12-02 03:23:59

In addPostItem you add the post to your client side list of models before you make the POST call. The newly created post you push onto the posts array will NOT have an _id, since it is generated on the server and not returned. As you pass the server an undefined _id to the server for this new post, any api calls against it will fail with the same error.

When you refresh the page and call your get function, all your posts have an _id so everything works correctly.

A typical pattern to follow would be to return created id (or the entire post) to the client on the post creation and then add that to your items array (something like this):

function addPostItem(post){
    triggerListeners();

    helper.post("/api/posts", post, function(res){
        posts.push(res.data);
    });
}

You'd also need to rewrite your POST request to return the created entity:

post.save(function(err) {
            if (err)
                return res.status(300).send(err, o);

            res.json(o);
        });

A variation would be to return just the ._id. Another would be to create the id on the client side, but then you lose some of the advantages of the native mongo ObjectIds.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!