Mongodb 如何更新映射类型为的嵌套对象
我想要更新映射类型模式的嵌套对象。 使用下面的代码,它不会改变任何东西。我尝试使用set、update、finedone和dupdate。但是他们中的任何一个都不起作用。 我真的很感激人们帮助我 模式:Mongodb 如何更新映射类型为的嵌套对象,mongodb,mongoose,Mongodb,Mongoose,我想要更新映射类型模式的嵌套对象。 使用下面的代码,它不会改变任何东西。我尝试使用set、update、finedone和dupdate。但是他们中的任何一个都不起作用。 我真的很感激人们帮助我 模式: const ColumnSchema = new Schema( { title: { type: String }, tasks: { type: Map, of: TaskSchema } <- I want to update this taskOrder
const ColumnSchema = new Schema(
{
title: { type: String },
tasks: { type: Map, of: TaskSchema } <- I want to update this
taskOrder: [{ type: mongoose.Schema.Types.ObjectId, ref: TaskSchema }] <- I want to update this
}
);
const DashBoardSchema = new Schema(
{
user: { type: mongoose.Schema.Types.ObjectId, ref: User },
dashBoardTitle: String,
columns: { type: Map, of: ColumnSchema },
columnOrder: [{ type: mongoose.Schema.Types.ObjectId, ref: ColumnSchema }]
}
这里是示例数据
enter code here
{
"columnOrder": [
"5e51860c45c55708cb441595"
],
"_id": "5e51860c45c55708cb441596",
"dashBoardTitle": "a",
"columns": {
"5e51860c45c55708cb441595": {
"taskOrder": [],
"_id": "5e51860c45c55708cb441595",
"title": "Second column",
"tasks": {}
}
},
"__v": 0
}
您需要通过以下方式更改查询:
let updateCond = {};
updateCond["$set"] = {};
updateCond["$set"]["columns."+columnId +".tasks"] = newTasks;
updateCond["$push"] = {};
updateCond["$push"]["columns."+columnId +".taskOrder"] = newTask._id;
const danshBoard = DashBoard.findOneAndUpdate(
{ _id: dashBoardId },
updateCond,
{ new: true },
(err, data) => {
if (err) console.log(err);
res.send(data);
}
);
{
"_id" : "5e51860c45c55708cb441596",
"columnOrder" : [
"5e51860c45c55708cb441595"
],
"dashBoardTitle" : "a",
"columns" : [
{
"id" : "5e51860c45c55708cb441595",
"data" : {
"taskOrder" : [],
"_id" : "5e51860c45c55708cb441595",
"title" : "Second column",
"tasks" : {}
}
}
],
"__v" : 0
}
顺便说一句:如果您以这种方式存储数据:
let updateCond = {};
updateCond["$set"] = {};
updateCond["$set"]["columns."+columnId +".tasks"] = newTasks;
updateCond["$push"] = {};
updateCond["$push"]["columns."+columnId +".taskOrder"] = newTask._id;
const danshBoard = DashBoard.findOneAndUpdate(
{ _id: dashBoardId },
updateCond,
{ new: true },
(err, data) => {
if (err) console.log(err);
res.send(data);
}
);
{
"_id" : "5e51860c45c55708cb441596",
"columnOrder" : [
"5e51860c45c55708cb441595"
],
"dashBoardTitle" : "a",
"columns" : [
{
"id" : "5e51860c45c55708cb441595",
"data" : {
"taskOrder" : [],
"_id" : "5e51860c45c55708cb441595",
"title" : "Second column",
"tasks" : {}
}
}
],
"__v" : 0
}
我们可以应用MongoDB特性
你能发布样本数据吗,Nodejs不清楚schema@Valijon谢谢你的评论我添加了样本数据非常感谢!它工作得很好。“更新”部分对我来说是新的。我很欣赏如何研究这项技术。mongoose文档中提到过这种技术吗?@ShinCat不幸的是,没有。mongoose是一个在Java中与MongoDB一样的Spring数据集成的框架。但是,您可以检查有关所有新功能的本地信息