1. 程式人生 > >mongodb.mongoose維護內嵌陣列元素

mongodb.mongoose維護內嵌陣列元素

執行環境:

- Nodejs
- MongoDB

文件例項名:

ProjectJob

文件格式如下:

{
    "_id" : ObjectId("5bc69eb0b298b33578bde0d8"),
    "title" : "專案名稱",
    "author" : ObjectId("5b694937dd0ca426403c5f2b"),
    "createdate" : ISODate("2018-10-17T02:30:08.021Z"),
    "jobs" : [ 
        {
            "_id" : ObjectId("5bc6d4703363941e30d6ccc7
"), "subject" : "專案子元素111" }, { "_id" : ObjectId("5bc6d4853363941e30d6ccc8"), "subject" : "專案子元素222" } ] }

 

新增子元素

var swhere = {_id: pjid};
var supdate =
{$addToSet: {jobs:{subject: job}}}
ProjectJob.findOneAndUpdate(swhere, supdate, {
new:true}, function(err){
  if (err) {
    res.end(JSON.stringify({code:
400, msg: "職位新增不成功"}));
    return;
  }

  res.end(JSON.stringify({code:
200, msg: "OK"}));
});

 

修改子元素

var swhere = {_id: pjid, "jobs._id": jid};
var supdate = {$set:{"jobs.$":{"subject": job}}};
ProjectJob.update(swhere, supdate, function(err){
  if (err) {     res.end(JSON.stringify({code: 400, msg: "更新不成功"}));return;   }   res.end(JSON.stringify({code: 200, msg: "OK"})); });

 

刪除子元素

var swhere = {_id: pjid};
var supdate = {$pull: {jobs: {_id: jid}}}
ProjectJob.update(swhere, supdate, function(err){
  if (err) {
    res.end(JSON.stringify({code: 400, msg: "刪除不成功"}));return;
  }
  res.end(JSON.stringify({code: 200, msg: "OK"}));
});