Sunday 30 April 2017

Updating sub array in JSON with a REST API in Mean Stack

I'm developing a MEAN stack application and I'm hung up on how to actually update a document that has been saved into the MongoDB already. I've seen that I have to use patch instead of post in my REST API paths, but it's still a little clouded to me. I want to insert a new Package into the Package JSON Array in the User JSON.

Possible Duplicate, but he's overriding a value in the array and not adding a new object into it.

My JSON Schema:

//User schema
const UserSchema = mongoose.Schema({
  name: {
    type: String
  },
  email: {
    type: String,
    require: true
  },
  username:{
    type:String,
    required: true
  },
  password:{
    type:String,
    required: true
  },
  packages: [{
    from: String,
    to: String,
    tracking: String

  }]
});

My REST API Paths

//Update
router.patch('/update', (req, res) => {
  const username = req.body.username;
  const packages = req.body.packages;

  User.getUserByUsername(username, (err, user) => {
    if(!user){
      return res.json({success: false, msg: 'User not found'});
    } else {
      User.addPackages(req.body.packages, (err, user) => {
        if(err){
          res.json({success: false, msg:'Failed to update packages'});
        } else {
          res.json({success: true, msg:'update packages'});
        }
      })
    }
  });
});
//Register
router.post('/register', (req, res, next) => {
  let newUser = new User({
    name: req.body.name,
    email: req.body.email,
    username: req.body.username,
    password: req.body.password,
    packages: req.body.packages
  });

  User.addUser(newUser, (err, user) => {
    if(err){
      res.json({success: false, msg:'Fail to register user'});
    } else {
      res.json({success: true, msg:'user registered'});
    }
  });
});

My Module's:

module.exports.addPackages = function(packages, callback){
  //Don't know how to push a JSON object into JSON Package array
}

module.exports.getUserById = function(id, callback){
  User.findById(id, callback);
}

module.exports.getUserByUsername = function(username, callback){
  const query = {username: username}
  User.findOne(query, callback);
}

module.exports.addUser = function(newUser, callback){
  bcrypt.genSalt(10, (err, salt) => {
    bcrypt.hash(newUser.password, salt, (err, hash) => {
      if(err) throw err;

      newUser.password = hash;
      newUser.save(callback);

    });
  });



via Stephen Lightcap

No comments:

Post a Comment