0

I have two schemas that are related to each other. And I am having trouble removing the related field. I have an article model and a note model and I would like to delete notes based on article id.

var article = new Schema({
title:{
    type:String,
    required:true
},
summary:{
    type:String
},
link:{
    type:String,
    required:true
},
note:{
    type: Schema.Types.ObjectId, 
    ref: 'Note' 

 }
})

var note = new Schema({
  title:String,
  body:String

})

So far I have tired do the following in my server.js file

var db = require("./models");

app.delete("/articles/:id",function(req,res){
    var id = req.params.id;
    db.Article.findById(id)
    .then(function(dbArticle){
        var noteId = dbArticle.note;
        db.Note.findByIdAndRemove(noteId);

        console.log("success")
    })
    .catch(function(err){
        res.json(err);
    })

So far I am not successful.

EDIT

app.delete("/articles/:id",function(req,res){
  var id = req.params.id;
   db.Article.findById(id)
     .then(function(dbArticle){
        var noteId = dbArticle.note;
        return db.Note.findByIdAndRemove(noteId);
    }).then(
        function(){
            res.json({ "message": "success" })
        })
    .catch(function(err){
        res.json(err);
    })

});

Zaynaib Giwa
  • 5,366
  • 7
  • 21
  • 26
  • 1
    `return db.Note.findByIdAndRemove(noteId); }).then( () => res.json({ "message": "success" }) ).catch(...` The function is still "async" and you need to wait for it to do something, and basically resolve the promise otherwise it does nothing. – Neil Lunn Nov 14 '17 at 02:15
  • Just as a note, it's really bad practice to do something like `var db = require("./models");` where that module clearly imports and exports all other models. Instead require only the needed model(s) directly. One day you might just want to "bundle" the code, and things like this make that process non-optimal as they "require everything". – Neil Lunn Nov 14 '17 at 02:18
  • @NeilLunn made the changes that you suggested and it gives me an empty object {}.I'll edit my question to reflect the changes that I made. I might have made a typo somewhere. – Zaynaib Giwa Nov 14 '17 at 02:44
  • @NeilLunn Made a typo. Thank you so much for your help. Still having trouble grasping the concept of async javascript. Do you know of any sources? – Zaynaib Giwa Nov 14 '17 at 02:50
  • 1
    [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) has a pretty good overview. – Neil Lunn Nov 14 '17 at 02:54

0 Answers0