Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 338
Jarnojr Avatar asked Sep 07 '25 22:09

Jarnojr


1 Answers

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?

like image 139
Kinglish Avatar answered Sep 09 '25 13:09

Kinglish