RoyalUp
RoyalUp

Reputation: 137

How can i delete _id properties?

My problem is im trying to delete ._id when i show the contacts with all properties but for some reason if doesnt work.

app.get("/contacts", (req,res)=>{
var id = res.params._id;
contacts.find({}).toArray((err,contactsArray)=>{

    if(err){
         console.log("Error: "+err);
    }else{
        var arraySinId = contactsArray.map((t)=>{
           t.delete(id);
        });
        res.send(arraySinId); 
    }
});

Upvotes: 0

Views: 69

Answers (1)

lankovova
lankovova

Reputation: 1426

You can remap array into a new one with properties that you need. Check out code below.

const contactsArray = [
  { id: 1, foo: 'foo'},
  { id: 2, foo: 'bar'},
  { id: 3, foo: 'baz'},
  { id: 4, foo: 'foobar'}
]

const arraySinId = contactsArray.map((t) => ({
  foo: t.foo,
}));

console.log(arraySinId)

UPDATE

In case the prop that has to be removed is dynamic you can use utility function omit that you can find in libraries such as Ramda or Lodash OR wite by your own.

const dynamicPropToRemove = 'id'

const contactsArray = [
  { id: 1, foo: 'foo'},
  { id: 2, foo: 'bar'},
  { id: 3, foo: 'baz'},
  { id: 4, foo: 'foobar'}
]

const arraySinId = contactsArray.map(R.omit([ dynamicPropToRemove ]));

console.log(arraySinId)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

Upvotes: 2

Related Questions