Reputation: 1727
I have the following code. Now when the constructor is called, the object gets created. Now when updating the field they are being updated like this. Note that I cannot modify the Comment()
because it is created by mongoose.
var newComment = new Comment();
newComment.content = req.body.content;
newComment.user.id = req.body.id;
newComment.user.name = req.body.name;
newComment.user.profilePicture = req.user.profilePicture;
newComment.votes.up = [];
newComment.votes.down = [];
newComment.comments = [];
newComment.timestamp = Date.now();
Is there a way to do something to update the object like this:
newComment.SOMEFUNCTION({
content = req.body.content;
user.id = req.body.id;
user.name = req.body.name;
user.profilePicture = req.user.profilePicture;
votes.up = [];
votes.down = [];
comments = [];
timestamp = Date.now();
});
Upvotes: -1
Views: 60
Reputation: 37005
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.
Object.assign( newComment, {
content : req.body.content,
user : {
id : req.body.id,
name : req.body.name,
profilePicture : req.user.profilePicture
},
votes.up : [],
votes.down : [],
comments : [],
timestamp : Date.now()
});
Upvotes: 3
Reputation: 3015
What's the reason for doing this? Is it just for organization purposes? If so then what's stopping you from just making a separate function:
var newFunc = function(newComment){
newComment.content = req.body.content;
newComment.user.id = req.body.id;
newComment.user.name = req.body.name;
newComment.user.profilePicture = req.user.profilePicture;
newComment.votes.up = [];
newComment.votes.down = [];
newComment.comments = [];
newComment.timestamp = Date.now();
};
You won't be able to safely change the Comment class, so if your intent is to maintain organization then this is a reasonable approach to keep from cluttering your constructor method
Upvotes: 1