简体   繁体   中英

Missing property at client side Nodejs

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!

The problem is that item is a MongooseDocument , not a plain javascript object.

There are multiple ways to achieve what you want.

1) Using .lean()

Documents returned from queries with the lean option enabled are plain javascript objects, not MongooseDocuments

Model.findOne().lean().exec((err, item) => {
    item.mention = [{ id: 1 }];
    res.json(item);
});

This option will increase the performance since you ignore the overhead of creating the Mongoose Document

2) Using: .set()

item.set('mention', [{ id: 1}], { strict: false });

4) Using spread operator

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

4) Using Object.assign as @Alexis Facques explained.

Taking advantage of Object.assign() should resolve your problem too.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM