2

I'm creating a mern app and new to mongodb/mongoose. And I'm currently using nested document model in my schema.

I was able to create elements in the nested document/subdocument by using push but I'm not able to return the newly pushed element as a value for post method.

Schema

var ProjectSchema= new mongoose.Schema({
    title:{
        type:String,
        required:true,
        unique:true
    },
    description:String,
    lists: [ListSchema]
})

var ListSchema= new mongoose.Schema({
     name: {
        type:String,
        required:true
    }
})

Creating lists in express api

listRouter.post('/api/project/:projectId/list/new', asyncMiddleware(async function(req,res,next){
        Project.findById(req.params.projectId, await function(err,items){
            items.lists.push(req.body)
            items.save();
            res.json(items.lists)
        })
}))

What happens is that after I create a new list, the return value is the array of all lists that exists in a given project not just the newly created lists. I only want the last created list.

I've tried items.lists.create(req.body, function(err, item)//...) instead of push but there is no post response. How do you create items in sub documents besides using push? so I can get the newly added value.

Ndx
  • 517
  • 2
  • 12
  • 29

1 Answers1

0

in your listRouter.post route you are sending response as res.json(items.lists)...this items.lists is the list of item that already exist for a given project.

you have to send response after new lists is pushed to project which would be look like this

    listRouter.post('/api/project/:projectId/list/new', asyncMiddleware(async function(req,res,next){
            Project.findById(req.params.projectId, await function(err,items){
                items.lists.push(req.body)
                items.save((err,newitems)=>{
                  if(err){
                     res.status(500).json(err)
                  }
                  else{
                     res.status(200).json(newitems.lists)
                  }

               });

            })
    }))