在Mongoose中创建的代码更新子文档不起作用。所以我试图更新Mongo Shell中的子文档。
这是文件(位置)和子文档(回顾):如何更新MongoDB中的子文档?
{
"_id" : ObjectId("56d8c73314fbc7e702cfb8c4"),
"name" : "Costly",
"address" : "150, Super Street",
"coords" : [
-0.9630884,
51.451041
],
"reviews" : [
{
"author" : "kyle riggen1",
"_id" : ObjectId("56d8de74cc7f953efd8455d9"),
"rating" : 4,
"timestamp" : ISODate("2015-06-01T06:00:00Z"),
"reviewText" : "will the ID work?"
}
],
"rating" : 0,
"__v" : 2
}
下面是一些我尝试在更新子文档:
This question gave this format:
update({
_id: "56d8c73314fbc7e702cfb8c4",
"reviews._id": ObjectId("56d8de74cc7f953efd8455d9")
},{
$set: {"reviews.$.rating": 1}
}, false, true
);
这回“更新未定义”的错误如下所示:
2016-03-03T22:52:44.445-0700 E QUERY [thread1] ReferenceError: update is not defined :
@(shell):1:1
我认为这是因为该命令没有与db.locations.update()开始
MongoDB documentation used this format:
db.locations.update(
{
_id: "56d8c73314fbc7e702cfb8c4",
review: { $elemMatch: { author: "kyle riggen1" } }
},
{ $set: { "location.$.rating" : 1 } }
)
这将返回一个有效的更新,但如图所示,更新并没有实际发生:
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
This question used this format:
db.locations.update({
_id: "56d8c73314fbc7e702cfb8c4",
'review.author': 'kyle riggen1'
},
{ $set: { 'review.$.rating': 1 }}
)
这将返回如下所示一样的MongoDB的文档:
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
所以这些查询我猜的工作,但我的数据不会得到更新。也许我的数据被索引错了?实际位置可以通过Mongoose API进行更新。
Woul'd你要借另一个打击选择是不会得罪任何人或以其他方式难堪你,当人们给简单的解释标题?当然这个解释是'ObjectId(“56d8c73314fbc7e702cfb8c4”)'。哎呀,你忘了投你的弦。 –
@BlakesSeven将题目固定为更恰当的问题。 ObjectId()只出现在我的mongo shell中。 API没有它就会生成一个ID。我编辑了我的问题来反映这一点。 – KyleRiggen
什么API?所有示例(以及每个错误和响应)都来自MongoDB外壳。在查询中传递给_id的值需要是ObjectId,否则它们不匹配。这正是这里发生的事情。只有像'mongoose'这样的东西才会自动为它分配一个字符串,因为它是模式类型,但是你没有在猫鼬中执行任何样本。 –