【问题标题】:Updating sub array in JSON with a REST API in Mean Stack使用平均堆栈中的 REST API 更新 JSON 中的子数组
【发布时间】:2017-09-28 13:52:16
【问题描述】:

我正在开发一个 MEAN 堆栈应用程序,我对如何实际更新已经保存到 MongoDB 中的文档感到困惑。我已经看到我必须在我的 REST API 路径中使用 patch 而不是 post,但它对我来说仍然有点模糊。我想将一个新包插入到用户 JSON 中的包 JSON 数组中。

可能Duplicate,但他覆盖了数组中的一个值,而不是向其中添加一个新对象。

我的 JSON 架构:

//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

  }]
});

我的 REST API 路径

//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'});
        }
      })
    }
  });
});

我的模块:

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);
}

他们正在更新到我的 MongoDB,但只是对象 ID 而不是值...

【问题讨论】:

    标签: json node.js mongodb express mongoose


    【解决方案1】:
    db.your_collection.update({},
                              {$set : {"new_field":1}},
                              {upsert:false,
                              multi:true}) 
    

    【讨论】:

    • 但是$set不是在增加一个新字段吗?
    • 它将添加新字段。如果您可以看到“new_field”是一个新字段,其值将被添加。欲了解更多信息,请访问此stackoverflow.com/questions/7714216/…。让我知道它是否有帮助。如果没有,我将创建一个示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    • 2014-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    相关资源
    最近更新 更多