Friday, 12 May 2017

Populate Object Array to Mongoose through API

I'm currently running into issues posting my data with array through the API using Mongoose.

Currently this data is showing in my console:

taskName: 'name',
  word: 'word2',
  wordDesc: 'description',
  tag: [ { text: 'word0' }, { text: 'word1' }, { text: 'word2' } ] }

I need the tag array to be pushed to the database with seperate values, so I can post/target each individual word into HTML for later usage.

Currently I add the whole array into my database collection, which is giving me this data on my database:

"word": "[object Object],[object Object],[object Object],[object Object]"

How do I loop through each item in my array and insert it individually to the database?

API code

 router.post('/task', function (req,res) {
            var task = req.body.tag;
            var taskDesc = req.body.wordDesc;
            var taskName = req.body.taskName;
            console.log(req.body);
            var newTask = new Task ({
                tags:[{word:task}],
                wordDesc: taskDesc,
                taskName: taskName 
            });


            newTask.save(function(err){
                if (err) {
                    return res.send(err);
                }
                return res.json(newTask);
            });
        });

MongoDB Schema

var taskSchema = mongoose.Schema({
    tags: [{
         word        : {type: String, default: ""}
    }],

    wordDesc    : {type: String, default: ""},
    taskName    : {type: String, default: ""}
});



via Amphrite

No comments:

Post a Comment