更新时我们需要发送所有的字段,而不仅仅是要更新的字段吗?
在做fullstackopen的练习的时候,对这个题目描述不解?当我们只需更新likes
字段,需要将其他的字段信息也放到请求中吗?
对这个项目做一个简短的介绍
使用到的一些技术: mongodb
、react
、axios
(用于前端和后端通信)、express
、restful
后端相关的操作如下所示
blogRouter.put("/:id", async (request, response) => {
const body = request.body;
const blog = {
title: body.title,
author: body.author,
url: body.url,
likes: body.likes,
};
const updateBlog = await Blog.findByIdAndUpdate(request.params.id, blog, {
new: true,
runValidators: true,
}).populate("user", { username: 1, name: 1 });
if (updateBlog) {
response.send(updateBlog);
} else {
response.status(404).end();
}
});
- 经过测试发现,
findByIdAndUpdate
应该只会更新我们通过参数传送的字段,而其他的会保持不变。 - 我使用
postman
测试,只需要发送一个likes
字段的信息就可以达到预期的效果,只更改了likes
字段,其他保持不变。
那为什么题目还说要发送所有的字段呢?
博客的schema定义
const mongoose = require("mongoose");
const blogSchema = new mongoose.Schema({
title: { type: String, required: true },
author: String,
url: { type: String, required: true },
likes: { type: Number, default: 0 },
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
});
// https://mongoosejs.com/docs/api/document.html#Document.prototype.toJSON()
blogSchema.set("toJSON", {
transform: (doc, ret) => {
// transform the unqiue identifier into a string representing.
ret.id = ret._id.toString();
delete ret._id;
// we don't require information about the mongodb version.
delete ret.__v;
},
});
module.exports = mongoose.model("Blog", blogSchema);
(脑子一时锈掉了)后端操作要提取出博客的author、url、likes等信息,如果我只包含likes的话,其他的值就是会是undefined,这些undefined将会作为值取更新对应的字段,所以要将其他的也一并包含。