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

后端 未结 1 1053
没有蜡笔的小新
没有蜡笔的小新 2021-01-24 23:37

I have a simple API in Express that allows the user to \'post\' and \'delete\' a post title into a MongoDB database. For some reason, when I add a post title, then subsequently

相关标签:
1条回答
  • 2021-01-24 23:57

    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.

    0 讨论(0)
提交回复
热议问题