如何使用_id从mLab集合更新对象 [英] how to update an object from mLab collection using _id
问题描述
我目前在后端有一个可以更新数组的api.问题是,它甚至不引用_id,而仅更新数组中的第一项.每当我编辑其他对象的值,然后单击更新时,它只会更新集合中的第一个对象.
I currently have an api in my backend that can update my array. The problem is, it doesn't even reference the _id and only updates the first item in my array. Whenever I edit the values for the other objects and then click on update, it only updates the first object in my collection.
这是代码:
router.route('carousel/update/:id').put(function(req, res) {
var data = req.body;
const myquery = {"_id": ObjectId };
db.collection("home").updateOne(myquery, {
$set: {
"img": data.img,
"header": data.header,
"subheader": data.subheader
}
}, (err, results) => {
res.status(200).json({status: "ok"})}
})
这段代码使我可以仅更新集合中的第一个对象.为了允许使用_id更新特定对象,我如何进行其他配置?我想念什么?
This chunk of code allows me to update the first only the first object in my collection. How do i configure it otherwise in order to allow updating specific objects using the _id? What am I missing?
编辑
查看其他堆栈溢出帖子后,这就是我所做的:
After looking at other stack overflow posts, this is what I did:
const myquery = {"_id" : ObjectId(req.params.id) };
但是现在我得到一个错误,说传入的参数必须是12个字节的单个字符串或24个十六进制字符的字符串.同样,当我控制台日志时,URL的':id'部分未定义.
But now I get an error saying 'argument passed in must be a single string of 12 bytes or a string of 24 hex characters. Also when I console log, the ':id' part of the URL is undefined.
推荐答案
您正在使用 updateOne
,它应为 updateMany
如下
You are using updateOne
its should be updateMany
as follows
db.collection("home").updateMany(myquery, {
updateOne
将更新第一个文档.
编辑
也请看这行
const myquery = {"_id": ObjectId }; is incomplete
应该是
const myquery = {"_id": ObjectId("some id") };
这篇关于如何使用_id从mLab集合更新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!