Nodejs-猫鼬子文档更新

时间:2020-08-18 08:56:36

标签: node.js mongodb mongoose

我可以添加,列出和删除我的架构,但是无法使用其自己的ID更新它。 我的尝试是在请求正文中获取数组的元素,清除旧数组并推送它们。

如何获取体内的数组并使用架构对其进行更新。

我的模型架构

const mongoose=require('mongoose');
const dateFormat = require('dateformat');
const now = new Date();
const Schema= mongoose.Schema;
const ProfileSchema=new Schema({
    profile_name:{
        type:String,
        required:true
    },
     //This is the place I want'to update
    books:[{
        activity_name:String,
     
        created_date:{ type: String, default: dateFormat(now, "dd/mm/yyyy")}
    },{
        usePushEach: true
    }]

});
module.exports= mongoose.model('profile',ProfileSchema );

我的路线

router.post('/addProfile', (req, res, next)=> {

  const {profile_name,book_name}=req.body;
  
  const profile=new Profile({
    profile_name
  });
  const promise=profile.save();
  promise.then((data)=>{
   

    for(let i=0;i<book_name.length;i++){
      profile.books.push(
          {
            book_name: book_name[i],

          }
      );
    }

    profile.save().then(()=>{
    });
    res.json({
      data:data,
      status:res.statusCode,
    });

  }).catch((err)=>{
    res.json({
      data:'',
      status:res.statusCode,
    });
    //next(err);
  });
});
 

router.put('/updateProfile/:profile_id',(req,res,next)=>{
  const {profile_name,book_name}=req.body;
  var count = Object.keys(book_name).length
  
  const promise= Profile.findByIdAndUpdate(
      req.params.profile_id,
      req.body,
      {
        new:true
      }
  );
  promise.then((profile)=>{
    if(!profile)
      next({
        data:''
      });
    res.json({
      data:profile,
      status:200
    });
    // **** This is the place I think I'm doing wrong way
    //reset the old array
    profile.books=[];

    //push elements to array
    for(let i=0;i<book_name.length;i++){
      profile.books.push(
          {
            book_name: book_name[i]
          }
      );
    }
    profile.save().then(()=>{
    });
  })
});

如何在不推送到数组的情况下更新子文档或数组

0 个答案:

没有答案