Thanh Minh
Thanh Minh

Reputation: 43

Cannot retrieve field mongoose in client side

My simple problem is:

I had an mongoose object at server side:

...
item = {
  name: "Test",
  id: 1
}

// item was an mongo schema

// id and name was define in model String and Number

Then I add into item new field mentions:

item.mention = [{ id: 1, ... }]

But I can't get mention at client side.

My response code:

res.json({ status: 1, message: 'success', data: item })

The response was data: { name: "Test", id: 1 }

I don't want to add mention into my mongo schema.

So, what's my problem?

How can I fix that?

Thanks!

Upvotes: 2

Views: 33

Answers (2)

nhaht
nhaht

Reputation: 1227

Try:

item = JSON.parse(JSON.stringify(item));

Before asign new prop for item.

Now you can asign value for new prop item.mention = some_value;

This will give you a new copy object that you can work with.

You cannot assign a new prop value to mongoose object which has not been defined before.

Upvotes: 0

Jim B.
Jim B.

Reputation: 4694

You can convert your mongoose document to an object first, then add your additional field.

Something like this:

let o = item.toObject();
o.mention = [{ id: 1, ... }];
res.json({ status: 1, message: 'success', data: o })

You could also just put this additional data in your response:

res.json({ status: 1, message: 'success', data: item, mention: [...] })

Upvotes: 1

Related Questions