Reputation: 1266
I'm a somewhat confused about the pull method from mongoose, can you only pull by objectID, or does the pull just have to be by a value from the data model?
Either way I'm failing to get the pull to remove elements from an Array.
Here are the models:
var fieldSchema = new Schema({
'name' : String,
'value' : String
});
var formSchema = new Schema({
'name' : String,
'fields' : [fieldSchema]
});
var userSchema = new Schema({
'email' : String,
'firstName' : String,
'lastName' : String,
'application' : [formSchema]
});
var fieldModel = mongoose.model('field',fieldSchema);
var formModel = mongoose.model('form',formSchema);
var userModel = mongoose.model('user',userSchema);
Code(there is only one doc in the DB which is why the findOne has no paramters):
userModel.findOne({}, function (err, user) {
if (err) return handleError(err);
var edit = false;
for(i in user.application) {
if(user.application[i].name == submit.name) {
edit = true;
user.application.pull({'name':submit.name}); //is this valid?
user.application.push(submit);
}
}
console.log(edit);
if(!edit) {
user.application.push(submit);
}
user.save(function(err, doc, numAffected) {
if (err) console.log(err);
else {
console.log('number of rows: ' + numAffected);
doc.save();
}
});
});
Doc in the DB:
"_id" : ObjectId("5490f0cdd059b4cdb6bdf7d2"),
"email":"[email protected]",
"firstName":"tester",
"lastName":"tester",
"application" : [
{
"name" : "Contact",
"fields" : [
{
"field_name" : "New field - 1",
"field_value" : "kkkkkkk"
}
]
}
],
Upvotes: 1
Views: 232
Reputation: 4700
change your second code with this code below,pull which you use isn't allowed because user.application is javascript array and there are no pull method to remove element from array .you can use $pull in mongoDB query ,it's not recomended to use for(i in user.application)
in this case
too
userModel.update({'application.name':submit.name},{$push:{application:submit}},function (err, user) {
if(user===0){
userModel.update({},{$push:{application:submit}},function(){
})
}
});
Upvotes: 1