Node.js 使用mongoose查询和更新深度嵌套对象
我有下面的模式Node.js 使用mongoose查询和更新深度嵌套对象,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我有下面的模式 const ButtonSchema = new mongoose.Schema({ conditions: mongoose.Schema.Types.Mixed }) // Data Model const DataSchema = new mongoose.Schema({ buttons: [ButtonSchema], __v: {type: Number, default: 0} }) //Question Model const Ques
const ButtonSchema = new mongoose.Schema({
conditions: mongoose.Schema.Types.Mixed
})
// Data Model
const DataSchema = new mongoose.Schema({
buttons: [ButtonSchema],
__v: {type: Number, default: 0}
})
//Question Model
const QuestionSchema = new mongoose.Schema({
data: [DataSchema],
__v: {type: Number, default: 0}
})
// Dialog Model
const Dialog = mongoose.model('Dialog', new mongoose.Schema({
name: String,
questions: [QuestionSchema]
}))
所以本质上,物体是这样的
{
"download_data": [
{
"__v": 0,
"data": [
{
"text": [
"xxxx"
],
"__v": 0,
"buttons": [],
"_id": "5afdf6cf1c1cc542c4580511",
"conditions": {
"false": {
"type": "endDialog",
"data": [
{
"text": []
}
]
}
}
}
],
"_id": "5afdf6cf1c1cc542c4580510",
"type": "confirm"
},
{
"__v": 0,
"data": [
{
"text": [
"xxxx"
],
"__v": 0,
"buttons": [],
"_id": "5afdf6cf1c1cc542c458050f"
}
],
"_id": "5afdf6cf1c1cc542c458050e",
"type": "endDialog"
}
]}
正如您所看到的,我有问题对象的唯一ID和数据对象的ID
在更新过程中,理想情况下,我只希望通过_id更新特定的数据字段
我可以通过这个来检索一个特定的问题
return DialogSchema.findOne({'questions._id': req.params.subId})
.then(function(data){
// this doesnt work
return data.questions[req.params.index].update(req.body)
})
.then(function(data){
console.log('data :', data)
})
.catch(function(err){
console.log('err: ', err)
})
但理想情况下,我只想检索DataSchema对象(作为数组对象插入QuestionsSchema对象)
但这不起作用
return DialogSchema.findOne({'questions.data._id': req.params.subId})
.then(function(data){
console.log('data : ', data)
})
.catch(function(err){
console.log('err: ', err)
})
有什么方法可以做到这一点吗?因为
问题架构
中的数据
字段是一个数组,所以不能仅访问子文档的嵌套属性。首先查询检索问题,然后必须稍微更新数据。首先,查询数据的不是模式而是模型实例。由于req.params.subId
是一个问题
Id,因此对该模型进行查询将更有效:
return Question.findOne({'_id': req.params.subId})
.then(function(question) {
...
})
但为了更新特定问题的数据,您需要更新问题模型,而不是数据模型:
...
.then(function(question) {
questions.data[req.params.index] = req.body
return question.save()
}
您需要这样做,因为子文档与其父文档一起保存。检查猫鼬文件
请注意,questions.data
应返回ObjectId
的数组,而不是数据
文档的数组。要解决此问题,可以使用populate()
方法,如下所示:
return Question.findOne({'_id': req.params.subId})
.populate('data')
.then(function(question) {
// Here questions.data is an Array of sub-documents
...
})
如有必要,您可以对填充的数据数组(Mongoose doc,)进行筛选或排序
只是对模式中的VersionKey(\uv)
的一点小评论。默认情况下,此属性由Mongoose设置。因此,您可以删除它们。检查猫鼬的文档,了解有关