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.