How to update all of an object's properties with spread syntax with Mongoose and Node

Cooper Brown Source

Thank you in advance, Im really stuck on this!

I have a User object in the database like such:

{
    "_id": {
        "$oid": "5a83470e722c1e00142e2216"
    },
    "first_name": "Test",
    "last_name": "User",
    "password": "$2a$10$FdsPkcjeLOpwfCRCHOSg6eqVDrDlbpi330tyG/Z.XPl3dKzX5K3s.",
    "email": "test.com",
    "role": 3
}

So I'm calling a function that is supposed to update an object, like a user just edited their profile. This is the body of my request:


{
    "userID": "5a83470e722c1e00142e2216",
    "employee": {
        "first_name": "TestNEW",
        "last_name": "UserNEW",
        "password": "$2a$10$FdsPkcjeLOpwfCRCHOSg6eqVDrDlbpi330tyG/Z.XPl3dKzX5K3s.",
        "email": "NEWUSER.com",
        "role": 3
    }
}

When I update the object, I want to $set or $update the entire user object, except for the _id. So, Im using this:

User.findOneAndUpdate({ _id: new ObjectID(req.body.userID)},
 { $set: { ...req.body.employee } }, function(err, user)...etc etc

But that doesnt work of course! So Im wondering how I can $set or $update (not sure which) all of the properties on the Object except for its _id, without using brute force like

{ $set: { first_name: req.body.employee.firstName, last_name: req.body.employee.lastName, ...etc etc etc } }
I know this way works, but I want to do it in a cooler way of course, can anybody help? Thank you!

javascriptnode.jsmongodbmongoosemongoose-schema

Answers

comments powered by Disqus