Mongoose Not Saving Data

后端 未结 6 2100
有刺的猬
有刺的猬 2021-01-14 01:50

I am having trouble with a simple query on my database. Following this tutorial: https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4 when Model.find() i

相关标签:
6条回答
  • 2021-01-14 02:02

    Exact same thing happened to me...

    First two POSTs succeeded but did not post the data I was sending:

    var p = new Post();
    p.result = 'hello-world';
    
    p.save(function (err) {});
    

    Turned on debug mode: mongoose.set('debug', true); and next POST the field was saved...

    Baffling!

    0 讨论(0)
  • 2021-01-14 02:07

    For this code

    post.title = req.body.title; // Set title (from request) post.content = req.body.content; // Set content (from request)

    could you check

    1. req.body.title and req.body.content are not undefined?
    2. do you set the field in your Post schema as

      var PostSchema = new Schema({ title: String, content: String });

    0 讨论(0)
  • 2021-01-14 02:10

    The problem is that you need to set the content-type while sending the post request as application/json otherwise the fields are not recognized.

    0 讨论(0)
  • 2021-01-14 02:15

    I am beyond confused right now. It suddenly works, the code is the exact same as above. I am going to leave this open in case someone stumbles across it one day and can solve this mystery.

    0 讨论(0)
  • 2021-01-14 02:17

    If you are using a manual tool like Postman to test your app, you must also put quotes around the key names in the body of your request, like {"key": "some string"}.

    If you just put {key: "some string"} then the whole key/value pair is ignored when the document is saved to the database.

    0 讨论(0)
  • 2021-01-14 02:18

    I experienced an error like this.

    The problem was that I was loading the wrong mongoose Schema.

    The result is that the only fields that are saved are those that are present in both schemas, i.e. _id and __v.

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