简体   繁体   中英

Express/Mongoose is only saving partial request data to database

I think this is related to how I've defined my schemas, but I can't seem to find where the bug is... I have an almost identical file set up that's working perfectly and I've unfortunately not been able to find a duplicate of this issue anywhere.

When sending an API request to my local Express instance via Postman, only the 'title' request body value is stored in the database. I am sending the following simple request to my route as Application/Json (thought the same happens when using x-www-form-urlencoded):

{
    "postTitle": "title goes here",
    "postContent": "body goes here",
    "isPublished": true
}

This is clearly being registered in express, as if I log the object I can see this data (plus timestamps and an _id):

{ _id: 5b07d9c0b8124e0599079c04,
  postTitle: 'title goes here',
  postContent: 'body goes here',
  isPublished: true,
  createdAt: 2018-05-25T09:39:12.869Z,
  updatedAt: 2018-05-25T09:39:12.869Z,
  __v: 0 }

However, when I send a get request to my route on this object using its ID, I receive the following in response:

{ "_id": "5b07d9c0b8124e0599079c04" }

Likewise, if I send a request to list all objects, I receive the following response:

{
    "posts": [
        {
            "_id": "5b07d9c0b8124e0599079c04"
        },
        {
            "_id": "5b07d9c0b8124e0599079c03"
        },
        {
            "_id": "5b07d9914f10ce058f137eba"
        }
    ]
}

Weirdly, sometimes the post title sent as part of the response is included in the response, and sometimes it isn't.

My schema is as follows:

var postSchema = new Schema({
  postTitle: String,
  postContent: String,
  isPublished: Boolean
},
{
  timestamps: true
});

My post API route for POST requests is as follows:

router.post('/posts', (req, res, next) => {
  var postTitle = req.body.postTitle;
  var postContent = req.body.postContent;
  var isPublished = req.body.isPublished;
  var newPost = new Post({
    postTitle: postTitle,
    postContent: postContent,
    isPublished: isPublished
  });
  newPost.save(function (error) {
    if (error) {
      console.log(error)
    }
    res.send({
      success: true,
      message: 'Post saved successfully!'
    })
  })
});

(If you're not using Router, you'll have 'app.post' instead of 'router.post') Again, this is a bit longwinded but everything works fine.

My GET route is as follows:

router.get('/posts', (req, res) => {
  Post.find({}, 'title content published', function (error, posts) {
    if (error) { console.error(error); }
    res.send({
      posts: posts
    })
  }).sort({_id:-1})
});

OK - so, by going through my code in detail I've figured out where I was going wrong and fixed the issue, however, in my searching I found very little in the way of results. I'm pretty new to Express, so I'm going to outline the cause of the issue and how I resolved it in order to potentially save someone else a bunch of time if they make the same stupid mistake.

Now, the issue I'm having results from the way I was retrieving the data and serving that in response to get requests. As an example, here's my GET route to list all of the objects.

I was entirely focusing on the post request and assuming it was a problem with the database. It turns out what I'd actually done, is in order to make my schemas and routes less confusing, I'd changed the names of the relevant variables. What I'd forgotten to do, however, is update this line in my GET route to reflect the change:

  Post.find({}, 'postTitle postContent isPublished', function (error, posts) {

Which I'd left as:

  Post.find({}, 'title content published', function (error, posts) {

The reason the title sometimes displayed is that I tried undoing changes back and forth to spot the issue.

I know this is a super basic query but I got stuck on this for the best part of a day, and the only other relevant discussion on this ended with OP saying that it magically fixed itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM