NetOperator Wibby
NetOperator Wibby

Reputation: 1404

Trying to save a nested object to my REST API

REST/API newbie here!

I want to save a list of things to a user, but I am not getting the desired response.

My mongoose schema looks like this:

var mongoose = require("mongoose"),
  mongooseSchema = mongoose.Schema,
  userSchema = {
    "name": String,
    "email": String,
    "cookies": {
      "cookie": [{
        "name": String,
        "brand": String
      }]
    }
  };

And (the messed up part of) my user route looks like this:

User.findById(req.params.id, function (err, user) {
    user.name = req.body.name;
    user.email = req.body.email;
    user.cookies = {
      "cookie": [{
        "name": req.body.cookies.cookie.name,
        "brand": req.body.cookies.cookie.brand
    }]
};

My response ends up being:

{
  "_id": "56048e38701a663707b49c7a",
  "__v": 0,
  "email": "[email protected]",
  "name": "NetOperator Wibby",
  "cookies": {
    "cookie": []
  }
}

I've been trying to get an API up and running for the past week and while inching further to success, am still not there yet. If anyone can shed some light onto why my code isn't working, I would greatly appreciate it.

EDIT: I updated my user update function to apply @ianaya89's code and still, no luck. Posted that function here in full.

function updateUser(req, res) {
  var updatedUser = {};
  updatedUser.name = req.body.name;
  updatedUser.email = req.body.email;
  updatedUser.cookies = {
    "cookie": [{
      "name": req.body.cookies.cookie.name
      "brand": req.body.cookies.cookie.brand
    }]
  };

  User.findByIdAndUpdate(req.params.id, updatedUser, {new: true})
    .exec(function(err, user) {
      if (err) {
        res.json({
          "ERROR": err
        });
      } else {
        res.json({
          "UPDATED": user
        });
      }
      //... your callback
    });
}

Upvotes: 0

Views: 914

Answers (1)

ianaya89
ianaya89

Reputation: 4233

I think that your code works ok but mongoose is returning the old user properties instead the new ones. So you can try with findByIdAndUpdate method and an approach like this:

var updatedUser = {};
updatedUser.name = req.body.name;
updatedUser.email = req.body.email;
updatedUser.cookies = {
  "cookie": [{
  "name": req.body.cookies.cookie.name,
  "brand": req.body.cookies.cookie.brand
}];

User.findByIdAndUpdate(req.params.id, updatedUser, {new: true})
  .exec(function(err, user){
    //... your callback  
  });

The third parameter of findByIdAndUpdate is a set of possible options, in this case I am setting it to return the updated user instead the old one: {new: true}.

Check out the documentation here.

Upvotes: 1

Related Questions