Jarnojr
Jarnojr

Reputation: 714

How do I remove the key from the populated field?

I have a Message schema:

const messageSchema = new Schema({
    receiver:{
        type: mongoose.Schema.Types.ObjectId,
        ref:'User'
    },
    sender:{
        type:mongoose.Schema.Types.ObjectId,
        ref:'User'
    },
    room:{
        type:String
    },
    message:{
        type:String
    }
},{timestamps:true});

As you can see I am holding a reference to sender.I am getting all messages using:

const messages = await Message.find({room}).sort({createdAt:1}).populate('sender',{email:1,_id:0});

and this returns:

[
{
    _id: 60b2725c3165d72d1a627826,
    receiver: 60abb9e1016b214c7563c8f1,
    sender: { email: '[email protected]' },
    room: '[email protected]@test.com',
    message: 'dfgfdsgdf',
    createdAt: 2021-05-29T16:57:00.857Z,
    updatedAt: 2021-05-29T16:57:00.857Z,
    __v: 0
  }
]

I want to remove the email key from the response. So the sender field should be like sender:'[email protected]'.Is there any way to do this?

Upvotes: 4

Views: 612

Answers (2)

Kinglish
Kinglish

Reputation: 23664

This is a special type of object and needs to be converted before we can work with it. Try this and see the link at the end

// messages is a special Mongoose object
const messages = [{
    _id: '60b2725c3165d72d1a627826',
    receiver: '60abb9e1016b214c7563c8f1',
    sender: {
      email: '[email protected]'
    },
    room: '[email protected]@test.com',
    message: 'dfgfdsgdf',
    createdAt: '2021-05-29T16:57:00.857Z',
    updatedAt: '2021-05-29T16:57:00.857Z',
    __v: 0
  }
]

// convert it to a normal object
let objs = messages.toObject()

// now we can iterate it 
let newobjs = objs.map(obj => {
  obj.sender = obj.sender.email;
  return obj
});


console.log(newobjs)

How do you turn a Mongoose document into a plain object?

Upvotes: 1

Favio Figueroa
Favio Figueroa

Reputation: 324

you can use this way and rewrite your object

 let obj = {
      _id: '60b2725c3165d72d1a627826',
      receiver: '60abb9e1016b214c7563c8f1',
      sender: { email: '[email protected]' },
      room: '[email protected]@test.com',
      message: 'dfgfdsgdf',
      createdAt: '2021-05-29T16:57:00.857Z',
      updatedAt: '2021-05-29T16:57:00.857Z',
      __v: 0
    };
    
    obj = {
      ...obj,
      sender: obj.sender.email,
    };
    console.log('obj',obj)

Upvotes: 1

Related Questions