如何使用猫鼬更新mongodb中的值?
我在节点js中做一个简单的MongoDB演示。
首先,我像这样保存我的document
,它工作正常。
{
"_id": "5d984cf947cd7301dab539be",
"tmObj": {
"a1": "N",
"a2": "N",
"a3": "N"
},
"__v": 0
}
现在我要更新一个attribute from my collection
示例数据是
const data = {
a1: "Y"
};
这是我的代码
app.get("/saveData", async (req, res, next) => {
try {
const data = {
tmObj: {
a1: "N",
a2: "N",
a3: "N"
}
};
console.log("before save");
let blog = new BlogPostModel(data);
let saveBlog = await blog.save(data); //when fail its goes to catch
return res.send(saveBlog);
} catch (error) {
console.log(error);
return res.status(400).send(error);
}
});
app.get("/update", async (req, res) => {
try {
const data = {
a1: "Y"
};
let filterBlog = await BlogPostModel.find({});
//when fail its goes to catch
console.log(filterBlog); //when success it print.
res.send(filterBlog);
} catch (error) {
console.log(error);
}
});
任何更新?
回答如下:这里是答案codesandbox
正如您在评论中提到的那样,集合中将只有一个文档,那么您可以使用一个空查询。要更新并取回文档,您可以使用findOneAndUpdate
:
app.get("/update", async (req, res) => {
try {
const data = {
a1: "Y"
};
let filterBlog = await BlogPostModel.findOneAndUpdate(
{},
{ "tmObj.a1": data.a1 }
);
//when fail its goes to catch
console.log(filterBlog); //when success it print.
res.send(filterBlog);
} catch (error) {
console.log(error);
}
});
为了避免弃用警告,您应该在{ useFindAndModify: false }
中添加选项mongoose.connect
。