如何使用mongoose orm从nodejs,mongodb中的子文档数组中删除特定元素

时间:2015-09-16 20:48:08

标签: node.js mongodb rest mongoose

首先,我想告诉我已经提供了理解和回答我的问题所需的所有代码。

现在来点请检查下面的json文件,我将在那里解释确切的问题

Modelfile1:TaskInfo Schema

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var taskInfo = mongoose.Schema({

     isactive:{type:Boolean}, 
     taskobject:{type:String}, 
     taskdetails:{type:String}, 
     iscompleted:{type:Boolean}

    });


    var TaskInfo = mongoose.model('TaskInfo', taskInfo);
    module.exports.TaskInfo = TaskInfo;
    module.exports.TaskInfoSchema = taskInfo;

模型文件2任务架构

var mongoose = require('mongoose');
var TaskInfoSchema = require("./taskinfo.js").TaskInfoSchema

var Schema = mongoose.Schema;

// Task schema
var taskSchema = mongoose.Schema({

 tasktype  : {type: String},
 createdon : {type: Date, default: Date.now},
 //createdby : {type: Schema.Types.ObjectId,ref: 'User'},
 //visitedby : [{type: Schema.Types.ObjectId,ref: 'User'}],
 taskinfo  : [TaskInfoSchema]  

});
module.exports = mongoose.model('Task', taskSchema); 

路由文件api.js:

var TaskInfo = require('../models/taskinfo.js').TaskInfo;
var Task = require('../models/task.js');
var config = require('../../config');
module.exports = function (app, express) {

    var api = express.Router();

    //GET method is for fetching all the tasks from the database,
    api.get('/taskdb', function (req, res) {

        //console.log("____");

        Task.find({}, function (err, taskdb) {

            if (err) {
                res.send(err);
                return;
            }
            res.json(taskdb);
        });
    });


    //POST method is for saving all the tasks to the database,
    api.post('/tasks', function (req, res) {

        var task = {};
        task.tasktype = req.body.tasktype;

        task.taskinfo = [];
        for (var i = 0; i < req.body.taskInfo.length; i++) {
            console.log(i);
            var taskInfo = new TaskInfo(req.body.taskInfo[i]);
            task.taskinfo.push(taskInfo);
        }

        var taskObj = new Task(task);

        taskObj.save(function (err) {
            if (err) {
                res.send(err);
                return;
            }
            res.json({
                message: 'Task has been created'
            })

        });
    });

//middleware 

    api.use('/tasks/:taskId',function(req, res, next){

      Task.findById(req.params.taskId, function(err, task){

        if(err){
           res.send(err);
        return;
               }
        else if(task)
        {
          req.task = task;
          next();
        }
        else
        {
        res.status(404).send ('no task found with such details');
        }
        });
    });


!-- // PATCH METHOD --! want to partial update array fields

//patch method--- wrong implementation (google how to patch array fields)
api.patch ('/tasks/:taskId',function(req,res){
 // if(req.body._id)
  //  delete req.body._id;

   if(req.body.tasktype)
 {
  req.task.tasktype =  req.body.tasktype; 
 }


  req.task.save(function(err){
        if(err){
           res.send(err);
        return;
        }
       res.json({message:'Task edited & updated '})

    });
});



//put method
api.put ('/tasks/:taskId',function(req,res){

//var task = {};
        req.task.tasktype = req.body.tasktype;

        req.task.taskinfo = [];
        for (var i = 0; i < req.body.taskInfo.length; i++) {
            console.log(i);
            var taskInfo = new TaskInfo(req.body.taskInfo[i]);
            req.task.taskinfo.push(taskInfo);
        }



        req.task.save(function(err){
        if(err){
           res.send(err);
        return;
        }
       res.json({message:'User info updated successfully'})

    });      

});

//put ends here

//Task deletion is working fine 

api.delete ('/tasks/:taskId',function(req,res){
       req.task.remove(function(err){
        if(err){
           res.send(err);
        return;
        }
       res.json({message:'Task has been deleted'})
  });
     });

api.get('/tasks/:taskId',function(req, res){

       res.json(req.task);
    });



    return api
}

Json文件:

[
  {
    "_id": "55f7a31c83dc2aa80b549516",
    "__v": 13,
    "tasktype": "Extreme",
    "taskinfo": [
      {
        "_id": "55f84a6e110db2bc0d5159a2",
        "iscompleted": false,
        "taskdetails": "This is task 1",
        "taskobject": "paid",
        "isactive": false
      },
      {
        "_id": "55f84a6e110db2bc0d5159a3",
        "iscompleted": false,
        "taskdetails": "This is task 2",
        "taskobject": "paid",
        "isactive": false
      },
      {
        "_id": "55f84a6e110db2bc0d5159a4",
        "iscompleted": true,
        "taskdetails": "This is task 3",
        "taskobject": "paid",
        "isactive": true
      },
      {
        "_id": "55f84a6e110db2bc0d5159a5",
        "iscompleted": false,
        "taskdetails": "This is task 4",
        "taskobject": "paid",
        "isactive": false
      }
    ],
    "createdon": "2015-09-15T04:48:28.631Z"
  }
]

好的,所以你现在看看json文件,假设我想从我的文档中删除第3个数组元素,以便json看起来像:

 [
      {
        "_id": "55f7a31c83dc2aa80b549516",
        "__v": 13,
        "tasktype": "Extreme",
        "taskinfo": [
          {
            "_id": "55f84a6e110db2bc0d5159a2",
            "iscompleted": false,
            "taskdetails": "This is task 1",
            "taskobject": "paid",
            "isactive": false
          },
          {
            "_id": "55f84a6e110db2bc0d5159a3",
            "iscompleted": false,
            "taskdetails": "This is task 2",
            "taskobject": "paid",
            "isactive": false
          },
          {
            "_id": "55f84a6e110db2bc0d5159a5",
            "iscompleted": false,
            "taskdetails": "This is task 4",
            "taskobject": "paid",
            "isactive": false
          }
        ],
        "createdon": "2015-09-15T04:48:28.631Z"
      }
    ]

当我尝试使用其id找到子文档时,它返回空的json文件,但使用父文档ID可以访问它们。我已经引用了mongodb文档,发现子文档以这种方式保存。

请告诉我一些删除特定数组元素的方法。

谢谢

0 个答案:

没有答案