【问题标题】:Update all model Express.js更新所有模型 Express.js
【发布时间】:2016-09-07 20:24:26
【问题描述】:

我想在 express 上使用 put 请求更新我的所有模型。 例如我在 mongoDB 中有一个这样的集合

{
    '_id': '123'
    'name' : 'jonh',
    'last' : 'smith',
    'email': 'js@dom.com',
    'phone': 'HTC',
    ...[more data]
}

使用 put 请求我发送新数据(不需要所有字段都存在) 在我的 index.js 中,我尝试过:

router.put('/update/:id', function(req,res){
  Perfiles.findByIdAndUpdate(req.params.id,req, function(err){
    if(err) { res.send(err);}
    res.json({messaje:'Done'});
  });
});

但我的收藏仍然没有变化。即使删除了其他字段我也想更新

{
    '_id': '123'
    'name' : 'Carl',
    'phone': 'iPhone'
}

【问题讨论】:

  • 在你的 findByIdAndUpdate 中你给 req 作为你的更新查询,但参数在 req.body 中
  • @Gatsbill 是的,我注意到发布后 5 分钟

标签: javascript json node.js mongodb express


【解决方案1】:

您将 req 对象作为要更新的值传递。但是 req 是什么?

Perfiles.findByIdAndUpdate(req.params.id,req, function(err){
    //what is req?
    console.log(req); 
    // it's a big express' object
})

您需要提供要更新的键和值,具体取决于您是从 url 的参数还是 url 的查询中发送值,或者如果您 POST 一个对象然后是 req.body

router.put('/update/:id', function(req,res){
  //since you POST the object then use req.body
  var newObject = { 
         name: req.body.name, 
         phone: req.body.phone
      }; 

  Perfiles.findByIdAndUpdate(req.params.id, newObject, function(err){
    if(err) { res.send(err);}
    res.json({messaje:'Done'});
  });
});

【讨论】:

    猜你喜欢
    • 2013-03-20
    • 2023-03-19
    • 1970-01-01
    • 2023-04-10
    • 2019-10-14
    • 2012-03-11
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    相关资源
    最近更新 更多