2

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

2 Answers 2

3

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

i used this and that help me to solve my problem field is dynamic so i need to use it in bracket.
use [field] do it for me.
1

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);
}

1 Comment

thanks for help but it left empty documnet .i don't need empty document

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.