1

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(user, req.body.packages, (err, user) => {
        if(err){
          res.json({success: false, msg:'Failed to update packages'});
        } else {
          res.json({success: true, msg:'update packages'});
        }
      })
    }
  });
});

My Module's:

module.exports.addPackages = function(user, packages, callback){
  User.findOneAndUpdate(
    {username:user.username},
    {$push: {"packages" : {
      "to" : packages.to,
      "from" : packages.from,
      "tracking" : packages.tracking
    }}},
    {new:true},
    function(err, newPackage){
      if (err) throw err;
    });
}

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

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

They're updating into my MongoDB, but just the object ID and not the values...

Community
  • 1
  • 1
Stephen
  • 1,072
  • 1
  • 19
  • 33

1 Answers1

1
db.your_collection.update({},
                          {$set : {"new_field":1}},
                          {upsert:false,
                          multi:true}) 
ManishKumar
  • 1,476
  • 2
  • 14
  • 22
  • But isn't `$set` adding a new field? – Stephen May 01 '17 at 14:29
  • It will add the new field. If you can see that "new_field" is a new field with value which will be added. For more information please visit this http://stackoverflow.com/questions/7714216/add-new-field-to-a-collection-in-mongodb. Let me know if it helps. If not, i will create an example. – ManishKumar May 03 '17 at 16:14