我一直在尝试通过 Node 应用程序中的 mongodb api 简单地更新 CosmosDB 文档,我一直在进行测试,没有错误,但无论如何值都不会更新。
我知道不支持更新数组元素,这很好,但这是一个顶级键值对。根本就不会发生没有任何错误的更改。
我一直在关注使用 CosmosDB + Mongoose + Node + Angular 的 Mean.js 项目,查看用于更新英雄的 API 并尝试其中的一些代码,但它仍然没有更新。
我一直在阅读文档,试图找出在 CosmosDB 中处理 CRUD 操作的默认方式以及它支持 MongoAPI 的哪些部分,但到目前为止还没有成功。
出于测试目的,我使用以下代码:
async function updateUser(id) {
try {
let user = await User.findById(id);
console.log (id);
console.log(user);
if (!user) return
user.id = id
user.firstName = 'ASDASDASASDASDASDASDASDA'
const result = await user.save()
console.log(result);
}
catch(err) {
console.log("There was an error updating user", err);
}
}
所以,我一直在尝试更多并设法使用以下代码更新英雄:
updateHero('10')
async function updateHero(id) {
const originalHero = {
uid: id,
name: 'Hero2',
saying: 'nothing'
};
Hero.findOne({ uid: id }, (error, hero) => {
hero.name = originalHero.name;
hero.saying = originalHero.saying;
hero.save(error => {
return(hero);
console.log('Hero updated successfully!');
});
});
}
现在我只是不确定为什么这实际上有效以及为什么以前没有。主要的不同之处在于我使用“uid”而不是 CosmosDB 分配的实际 ID。
最佳答案
我测试了您提供的示例代码,它们都成功更新了文档。
示例文档:
片段一:
updateUser('5b46eb0ee1a2f12ea0af307f')
async function updateUser(id) {
try {
let user = await Family.findById(id);
console.log (id);
console.log(user);
if (!user) return
user.id = id
user.name = 'ASDASDASASDASDASDASDASDA'
const result = await user.save()
console.log(result);
}
catch(err) {
console.log("There was an error updating user", err);
}
}
输出一:
片段二:
updateFamily('5b46eb0ee1a2f12ea0af307f')
async function updateFamily(id) {
const updateFamily = {
_id: id,
name: 'ABCD',
};
Family.findOne({ _id : id }, (error, family) => {
family.name = updateFamily.name;
family.save(error => {
console.log(JSON.stringify(family));
console.log('Hero updated successfully!');
return(family);
});
});
}
输出二:
此外,您可以使用db.collection.update()
来更新文档。
db.families.update(
{ _id: '5b46eb0ee1a2f12ea0af307f' },{ $set:
{
name: 'AAAA'
}
})
更多详情,请引用文档:https://docs.mongodb.com/manual/reference/method/db.collection.update/
希望对您有帮助。
关于node.js - Cosmos DB + Mongo API,更新文档解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51283473/