这是我在猫鼬中的嵌套模型。
const lessonSchema = new mongoose.Schema({
name: { type: String, required: true },
sentences: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Sentence',
required: true,
},
],
})
const sentenceSchema = new mongoose.Schema({
name: { type: String, default: '' },
words: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Word',
required: true,
},
],
})
json:
// Lesson
{
"_id": "60af7f9aee856442a8ca786a",
"name": "Lesson name"
"sentences": [
{
"name": "sentence one",
// other fields
"words": [
{
"_id": "60af7f9aee856442a8ca7863",
"word": "any text",
// other fields. I need words ids, can't use simple array.
},
{
"_id": "60af7f9aee856442a8ca7864",
"word": "user input",
},
{
"_id": "60af7f9aee856442a8ca7865",
"word": "lorem",
}
],
"_id": "60af7f9aee856442a8ca7868",
},
// array of sentences
]
}
可以通过在所有数组数组中添加、编辑或删除来更改任何字段。
const filter = { _id: req.params.id } // get Lesson ids from url parameters
const updateData = req.body // received data from user input
const options = { upsert: true, new: true }
Lesson.findOneAndUpdate(filter, updateData, options)
首先,使用 findOneAndUpdate 是个好主意吗? 我试过 $ 运算符,但我的问题是如何映射值? 谢谢。