Reputation: 1068
I am new to MongoDb, and I have a question about the 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 don't know what is the problem.
My user table is shown below:
Upvotes: 1
Views: 48
Reputation: 9268
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.
Upvotes: 2