【问题标题】:PUTMAPPING JAVA SPRING BOOT MONGODB REST API - update not working but creating a new entryPUTMAPPING JAVA SPRING BOOT MONGODB REST API - 更新不起作用但创建一个新条目
【发布时间】:2021-11-05 03:13:39
【问题描述】:

当尝试使用 PostMapping 和 PUT 请求更新 mongo db 表中的现有条目时,每次我尝试更新表中都会创建一个新条目..

以下是我的代码 控制器

@RestController
@RequestMapping("/expenses")
public class mydataExpController {

@PutMapping("/")
    public mydataExpense updExpenses(@RequestBody mydataExpense exp){
        return expenseServices.updData(exp);
        
}

服务

@Service
public class ExpenseServices {
    @Autowired
    mydataExpRepository mydataexprepository;

public mydataExpense updData(mydataExpense exp) {
        return mydataexprepository.save(exp);
    }

存储库

@Repository
public interface mydataExpRepository extends MongoRepository<mydataExpense, String> {
    

}

在邮递员中

connection →keep-alive
content-type →application/json
date →Tue, 29 Dec 2020 10:54:51 GMT
keep-alive →timeout=60
transfer-encoding →chunked

每次我使用 PUT 执行 http://localhost:8080/expenses/

在数据库中创建一个新条目

【问题讨论】:

  • 你能添加一个示例内容吗?很可能您没有正确传递 id 字段。
  • 请看传递的内容和响应
  • { "_id": "5fedba90e11a563ce37e9890", "expdate": "12-24-2020", "exptyp": "Biriyani Hub", "expamt": 0 }
  • { "expdate": "12-24-2020", "exptyp": "Biriyani Hub", "expamt": 0 }

标签: java mongodb spring-boot microservices rest


【解决方案1】:

我认为它创建了一个新对象,因为您只是将它直接传递给 repo.save()。

首先您应该找到一个现有的 myDataExpense,并对其进行修改/更新,然后调用 repository.save()。

仅供参考,您也可以使用 mongoTemplate 执行类似的操作。

Query query = Query.query(Criteria.where("<id attribute name of your myDataExpense Document>").is(exp.getId);
Update update = new Update().set(".....$", exp);
mongoTemplate.updateFirst(query, update, myDataExpense.class);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    • 2017-11-03
    相关资源
    最近更新 更多