NIKHIL PARIHAR
NIKHIL PARIHAR

Reputation: 532

Remove element from array in mongoose

i am working on nodejs/express

I want to delete element in array in mongoose

i have document in this format

{ 
    "_id" : ObjectId("5a2e19223e50551504b316c0"), 
    "username" : "nikhil", 
    "email" : "[email protected]", 
    "password" : "$2a$10$f3NvrTywIezlzKcZLWSU0O98gn6Mc.Q8B0ZNEDG2F66f4rwyo65Yu", 
    "companyname" : "itr", 
    "role" : "vendor", 
    "verify" : "true", 
    "createddate" : ISODate("2017-12-10T18:30:00.000+0000"), 
    "account" : [
        {
            "Region" : [
                "North America", 
                "Africa", 
                "Asia"
            ]
        }, 
        {
            "Category" : [
                "Group 1", 
                "Group 2", 
                "Group 3"
            ]
        }
    ]
}

i want to remove only Region field using mongoose query i m getting data dyanamically so user can delete any array either it is Region or Category. i m getting array name which i want to delete in parameter "field".

module.exports.setupAccount = function(id,field,callback){
        var query = { _id: id};
        User.findOneAndUpdate(query,{ $set: { account.Region:[] }}, callback);
}

i am new to nodejs and mongoose thanks in advance

Upvotes: 2

Views: 5671

Answers (2)

dnickless
dnickless

Reputation: 10918

If you don't want to keep the empty document after removing the field you can simply $pull the entire element from the array:

module.exports.setupAccount = function(id,field,callback){
    var query = { _id: id };
    User.findOneAndUpdate(query, { $pull: { "account": { field: { $exists: true } } } }, callback);
}

Upvotes: 3

s7vr
s7vr

Reputation: 75994

You can use below function.

Use computed property names to dynamically pass the field to unset and query expression.

Query to verify for array existence followed by $unset to remove array.

$ positional operator to dynamically locate array based on query criteria. You can hardcode the array index if you know the array position.

module.exports.setupAccount = function(id, field, callback){
   var query = { "_id": id, ['account.' + field]:{"$exists":true}};
   var unset = {"$unset":{['account.$.' + field]:""}};
   User.findOneAndUpdate(query, unset, callback);
}

Upvotes: 1

Related Questions