问题
I want to updates only one element in the document to use put request
I tried
PUT localhost:3000/api/memo/5b8e382d61984255d879f872
{
text: "updated!"
{
but, it updated like this
{
text: "updated!",
imgUrl: null,
tag: null,
...
}
Is there a way to updates one element in document?
await Memo.where('_id')
.equals(req.params.id)
.updateOne({
imgUrl: req.body.imgUrl,
text: req.body.text,
tag: req.body.tag,
user: req.body.user,
loc: req.body.loc
})
回答1:
You can use the following solution to update only one element:
Memo.updateOne(
{ "_id" : ObjectId("5b8e83957d56e802274d6") },
{ $set: { "text" : "updated" } });
UpdateOne() updates the first matching document in the collection that matches the filter.The above query operation updates a single document where text: "updated".
The operation can either replace an existing document or update specific fields in an existing document.
来源:https://stackoverflow.com/questions/52165805/mongodb-how-to-update-only-one-element-in-the-document