如何推送项目嵌套数组猫鼬

时间:2019-01-29 06:10:28

标签: node.js mongodb mongoose nested

我在link处找到了问题的答案。添加成功,但是我有问题。如果您能帮助我,我会很高兴。我是MongoDb的新人

类别模型

var childSchema = new Schema({name:String});
var categoryschema = new Schema({
_id: { type: Schema.ObjectId, auto: true },
name:  String,
children: [{name:{type:String}}], 
});
var category = mongoose.model('Category', categoryschema);
module.exports = category; 

categoryAPI.js

exports.addCategory = function (req, res) {

    var parentId = req.body.category.parentId;
    var id = req.body.category.id;


    category.updateOne({_id:parentId, 'children._id':id}, {$push : 
            {'children.$.0' : {"id":mongoose.Types.ObjectId,"name":req.body.name}}
        }, {upsert: true}, function(err, docs){
        res.json(docs);
        console.log(docs);
        });
}

在我使用时添加此内容('children。$。0') enter image description here

我想要这个。但是当我使用它时它不会添加(children。$。children) enter image description here

0 个答案:

没有答案