1

Trying to find a single document details by id using POST API but API returns error 500 using MongoDB and Node.js.

Schema

    {
    "_id": {
        "$oid": "5cad89cabfb35db56688556c"
    },
    "articleid": "c4a3c72a-f4ec-11e7-bec2-b083fe9a696b",
    "md5id": "8e0d6ca665a977cc825bd90dc1751d53",
    "headline": "Stepping up",
    "subtitle": "",
    "type": "PRINT",
} 

Model.js

var mongoose = require('mongoose');

var schema = new mongoose.Schema({

Title: String
 },
{
    collection: 'impactliveupdated'
});

module.exports = mongoose.model('Model', schema);

controller.js

  articlesById = function (req, res) {
  var articleids = req.body.articleids;
  var query = {

  };
  query.articleid = {
      $in: articleids
  }; 

  articlesModule.findOne(query, function (err, impacts) {
      if (err) {
          console.log("error 6");
          console.log(err);
          res.status(500);
          res.send("internal error");
      } else {
          res.status(200);
          console.log("sending data");
         // console.log(impacts);
          res.json(impacts);
      }
  });
} 

if possible guide me to correct it I am new in MEAN stack!

8
  • Is articleId in the schema? Not showing in code. Commented Jun 25, 2021 at 8:13
  • yes articleId is in document field Commented Jun 25, 2021 at 8:15
  • Your schema only shows one field Title. Are you confusing _id with articleid? You can use findById too. Commented Jun 25, 2021 at 8:16
  • 1
    @TusharShahi I have a field name articleid by which i am trying to find, do i need to mention articleid in Model.js schema ? Commented Jun 25, 2021 at 8:17
  • 1
    Yes. it is better if you do it. Also, i was asking about articleIds. $in operator works on arrays right. If articleId from the document is inside [articleIds] which is sent in your request body it will return the doc. Commented Jun 25, 2021 at 8:24

1 Answer 1

1

Firstly, you don't need to use $in operator as suggested by @Tusharshahi and you can use direct findOne query.

  articlesById = function (req, res) {
  var articleid = req.body.articleid; 

  articlesModule.findOne({articleid:articleid}, function (err, impacts) {
      if (err) {
          console.log("error 6");
          console.log(err);
          res.status(500);
          res.send("internal error");
      } else {
          res.status(200);
          console.log("sending data"); 
          res.json(impacts);
      }
  });
} 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.