midhun k midhun k - 3 months ago 14
Node.js Question

Insertion into array in mongo not happening?

I am new to MongoDb, and i have a doubt in insertion of data. My mongoose schema for 'user' collection:

var user = new mongoose.Schema({

username : {type: String},
email : {type: String,index: {unique: true}},
password : {type: String},
feed : [{
title : {type: String},
description : {type: String},
latitude : {type:Number},
longitude : {type:Number},
feedImages : [{
imageUrl: {type: String}
}]
}]
});


I want to insert data to the feedimages and my service for that is:

app.post('/uploadFeedImage',function(req,res) {
var _id = req.body._id;
var imageUrl = req.body.imageUrl;
db.user.update(
{"feed._id":_id },
{$push : {
feedImages:{
imageUrl:imageUrl
}
}
},function (err,result) {
if (err) {
res.json({"success": '0', "message": "Error adding data"});
}
else {
res.json({"success": '1', "message": "Data added"});
}
});
});


But the data is not inserted into table and no error is shown, I dont know what is the problem. Please help me...

My user table is shown below:

TABLE

Answer

use $ to push in the matched element of the array. i.e. for which feed._id matches

Try this:

db.user.update(
        {"feed._id":_id },
        {$push : {
            "feed.$.feedImages":{
                imageUrl:imageUrl
            }
        }
        },function (err,result) {
            if (err) {
                res.json({"success": '0', "message": "Error adding data"});
            }
            else {
                res.json({"success": '1', "message": "Data added"});
            }
        });

Edit

$ is update positional operator, which helps update only the element which matches the update criteria. For more info see MongoDB $ operator Documentation.