1

//Here is model

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

// 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  : [{ isactive:Boolean, taskobject:String, taskdetails:String, iscompleted:Boolean}]  

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

// route

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

    var api = express.Router();

  api.post('/tasks', function (req, res) {
    var task = new Task({
 // ...
 tasktype  : req.body.tasktype,
 taskinfo  : req.body.taskinfo,
      }); 

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

While all other fields getting saved but the one with array with multiple fields always return blank like "taskinfo : [ ] "

The post method is REST API to post a task into mongoose database, for array with single field everything working fine but array with multiple field is not getting saved, someone please help me here.

Basic help will be fine, just please teach me how to save "multiple field array".

Mongoose doesnot always require subdocument structure and this can be achieved by the above model, please dont advice to use subdocument structure, I want to learn this.

Thank You.

Madhur Gupta
  • 75
  • 1
  • 11
  • It looks like you have lost some code near line 9 on `route`. Please check. – maowtm Sep 13 '15 at 02:04
  • I am asking logic for saving array as I dont know how to save array with multiple fields, createdon is saved by default and i am not concerned about other fields right now. – Madhur Gupta Sep 13 '15 at 02:06
  • Does `markModified` works? – maowtm Sep 13 '15 at 02:06
  • i.e. `doc.markModified("taskinfo")` – maowtm Sep 13 '15 at 02:08
  • I am very much new to it, what i learn from all the lecture over net from udemy or pluralsight is for each field type fieldname : res.body.fieldname.. Can you tell me complete logic for multiple field array ? – Madhur Gupta Sep 13 '15 at 02:10
  • let me try it just one min pls – Madhur Gupta Sep 13 '15 at 02:11
  • try to add a `doc.markModified("taskinfo")` before saving. Will that work? – maowtm Sep 13 '15 at 02:13
  • Connected to the database POST /api/tasks 500 57.358 ms - 1560 ReferenceError: doc is not defined at C:\projects\rt\app\routes\api.js:17:1 at Layer.handle [as handle_request] (C:\projects\rt\node_modules\express\lib\router\layer.js:95:5) at next (C:\projects\rt\node_modules\express\lib\router\route.js:131:13) at Route.dispatch (C:\projects\rt\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] and so on – Madhur Gupta Sep 13 '15 at 02:29
  • `doc` means `task`. Please do `task.markModified("taskinfo")`. – maowtm Sep 13 '15 at 02:33
  • nope its not working,Still producing same result taskinfo empty array, can you tell me basic how to store multiple field array (not subdocument structure) ? – Madhur Gupta Sep 13 '15 at 02:48
  • [ { "_id": "55f4e4f5fe8b36980a611519", "tasktype": "Basic", "__v": 0, "taskinfo": [], "visitedby": [], "createdon": "2015-09-13T02:52:37.512Z" } ] – Madhur Gupta Sep 13 '15 at 02:53

1 Answers1

5

I think if taskinfo has a multiple values and you want to save it as embedded document inside task document. You should have different document of task info. So,you can save like that

var TaskInfoSchema = require("taskInfo.js").TaskInfoSchema

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);

And now you will have different document as task info like

var taskInfo = mongoose.Schema({

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

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

When you will save task document,

 Var TaskInfo = new TaskInfo({
          isactive:true, 
          taskobject:"", 
          taskdetails:"", 
          iscompleted:true
    })



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

you can push it

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

Then you will save task document

var taskObj = new Task(task);

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

    });
});
Prabjot Singh
  • 4,491
  • 8
  • 31
  • 51
  • Thanks for a good description sir, but i have read somewhere that embedded document is not required, can you tell me how to achieve this by creating single schema, also can you suggest me some book or course from where i can learn about inserting array field in mongodb using mongoose. http://stackoverflow.com/questions/15208711/mongoose-subdocuments-vs-nested-schema – Madhur Gupta Sep 13 '15 at 13:32
  • Here is how i want my json document: http://www.jsoneditoronline.org/?id=118a16030d6d3394f6dab4fdcd31b6fe – Madhur Gupta Sep 13 '15 at 14:01
  • please follow this link before design your schema http://blog.mongodb.org/post/87200945828/6-rules-of-thumb-for-mongodb-schema-design-part-1 – Prabjot Singh Sep 14 '15 at 05:26
  • I have tried your ans, but error popsup, someone said i have to use push to enter & save array. – Madhur Gupta Sep 14 '15 at 11:30
  • also Var TaskInfo = new TaskInfo({ isactive:true, taskobject:"", taskdetails:"", iscompleted:true }) here why we arenot taking input from user ? – Madhur Gupta Sep 14 '15 at 12:43
  • yes you can take it,i declared fields empty as i don't know what will be you get from user..and please taskinfo file require in task domain..i have updated answer..please let me know..what is the status ? – Prabjot Singh Sep 14 '15 at 12:51
  • Sir, I am still facing multiple errors, cannot find module taskinfo.js – Madhur Gupta Sep 14 '15 at 13:19
  • can you help me via teamviewer still same error pop, i have given right path – Madhur Gupta Sep 14 '15 at 13:31
  • Sorry,i could not help you via teamviewer. but if you can push your code on public repo or you can send me your code on email... prabhkahlon429@gmail.com,i can help... – Prabjot Singh Sep 14 '15 at 13:38
  • i am sending mail, just give me a moment please – Madhur Gupta Sep 14 '15 at 13:44
  • I have sent you a mail please check, there is no frontend code as i am using postman client to check post and get api's – Madhur Gupta Sep 14 '15 at 14:06
  • Thanks for helping me at this level, i will wait for your reply. – Madhur Gupta Sep 14 '15 at 14:19