我有一個 mongo 集合,如下面的代碼:
const ExerciseSchema = new Schema({
name: { type: String, required: true },
exercise: [
{
exerciseId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: Exercise,
},
period: { type: String, enum: ["day", "night"], required: true },
},
],
timestamp: { type: Date, default: Date.now() },
});
當我嘗試同時插入多個練習時,考慮到我的練習是一個陣列,mongo 只保存第一個暫存器。例如,我嘗試插入:
{
"name": "Exercise 1",
"exercise": [
{
"exerciseId": "1",
"period": "night"
},
{
"exerciseId": "1",
"period": "day"
}
]
}
并且,保存后,get 方法回傳給我:
[
{
"timestamp": "2021-11-30T14:18:42.455Z",
"_id": "1",
"name": "Exercise 1",
"exercise": [
{
"exerciseId": "1",
"period": "night",
}
],
"__v": 0
}
]
也就是說,貓鼬只保存陣列中的第一個暫存器。有誰知道為什么會這樣? 從控制器聽到我的 create 方法:
exports.create = (req, res) => {
const {
name,
exercise: [{ exerciseId, period }],
} = req.body;
const newExercise = new Exercise({
name,
exercise: [{ exerciseId, period }],
});
newExercise.save((err, data) => {
if (err) {
res.status(500).send({ message: err });
return;
}
res
.status(200)
.send({
message: "Success",
});
});
};
Obs:我指的是控制器中的“new Exercise(...)”
uj5u.com熱心網友回復:
使用它來更新陣列:
parent ---> a mongooose doc
parent.child.push({new child object});
parent.markModified('child');
parent.save();
在你的情況下 child 是運動陣列和 parent.markModified('child'); 你必須把 parent.markModified('exercise');
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/371146.html
