Arghadeep Dey
Arghadeep Dey

Reputation: 53

MongoDB: findOne returns null but sub document exists in collection

I am adding custom list in db. After Calling a random custom list, the custom list created with sub document list in db. But it's showing it's sub document in console is null. My code ->

My Sub document Scheme->

const toSchema=new mongoose.Schema({
  name:{ type:String,required:true}
});

My main custom list Schema->

const newSchema=new mongoose.Schema({
  name:String,
  sch:[toSchema]
});
const Work=mongoose.model("work",newSchema);

Now, I adding the collections & show it to console->

app.get("/post/:get",function(req,res){
  var ch=req.params.get;
  const item=new Todo({
    name:ch
  }); 
  const work=new Work({
    name:ch,
    sch:item
  });
  work.save();
  Work.findOne({name:ch},function(err,works){
    if(err){
      console.log(err);
    }
    else{
      console.log(works);
     }
 
});  
});

I am typing a custom list "home" & it's created successfully in db. But the sub document showing null.

Console output which was showing the null value instead of the sub document

Here the sub document created which was shown in mongoDB

Please, help.

Upvotes: 0

Views: 803

Answers (2)

Tanixq
Tanixq

Reputation: 1

It is showing null because in your Schema you declared sch as a array and trying to store object in it.

  const newSchema=new mongoose.Schema({
  name:String,
  sch:[toSchema] // Declared Array

});
const Work=mongoose.model("work",newSchema);

That is why it is null. If you want store object in it (In your case const item) then you need to declare sch as a object. Change your newSchema as mentioned below

const newSchema = new mongoose.Schema({
  name:String,
  sch:{toSchema}
});
const Work=mongoose.model("work",newSchema);

Then it works.

Upvotes: 0

Shivam
Shivam

Reputation: 3642

It shows null because .save() is asynchronous in nature, so you need to wait for it's execution to complete before trying to find, but if you just want to find the document you are saving, then you don't need to use find as .save() returns the document you are saving

 work.save(function(err, document) {
    if (err)
      console.error(err);
    else
      console.log(document);

  });

But if you are planning to use .find() you need to wait for .save() execution to finish

Upvotes: 1

Related Questions