zoukankan      html  css  js  c++  java
  • 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"}));
    });
  • 相关阅读:
    docker入门
    spring aop切面入门
    java 拉姆达 lamdba get
    Spring 3
    Spring 进阶二
    腾讯云 视频 点播 视频上传接口
    js 实时获取后台数据 Spring
    Spring 进阶一
    hibernate 第四天 重点查询的方式
    hibernate 第三天
  • 原文地址:https://www.cnblogs.com/visionsl/p/9803943.html
Copyright © 2011-2022 走看看