猫鼬:如何插入单个子文档-不是数组 [英] mongoose: How to insert a single subdocument - not an array

查看:70
本文介绍了猫鼬:如何插入单个子文档-不是数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在猫鼬中,您可以按照以下说明为子文档声明架构:

In mongoose you are able to declare a schema for a subdocument as per:

        var childSchema = new mongoose.Schema({ name: String, age: String });
        var parentSchema = new mongoose.Schema({
            children: [childSchema]
        });
        var Parent = mongoose.model('Parent', parentSchema);
        var Child = mongoose.model('Child', childSchema);

        var child = new Child({name:'Joe', age: '21'});
        var parent = new Parent();

        parent.children = [child];

        parent.save(function(err, saved) {
            if(err) console.error(err);
        });

似乎子文档类型需要为数组.我需要能够将子文档保存为单个实例,而不是数组,即:

Seems the subdocument type needs to be an array. I need to be able to save the subdocument as a single instance, not an array ie:

        var childSchema = new mongoose.Schema({ name: String, age: String });
        var parentSchema = new mongoose.Schema({
            children: childSchema // not an array
        });
        var Parent = mongoose.model('Parent', parentSchema);
        var Child = mongoose.model('Child', childSchema);

        var child = new Child({name:'Joe', age: '21'});
        var parent = new Parent();

        parent.children = child; // not an array

        parent.save(function(err, saved) {
            if(err) console.error(err);
        });

因此不是数组或引用,而只是单个实例子文档.这可能吗?如果没有,我应该使用:

So not an array or a ref, just a single instance subdocument. Is this possible? If not should I use:

var childInstance = child.toObject();

推荐答案

有时很难看到明显的东西.您不需要其他架构即可实现所需的功能.您可以像这样在父架构中简单地定义子文档:

Sometimes it is hard to see obvious. You do not need another schema to achieve what you want. You can simply define your sub document within your parent schema like this:

    var parentSchema = new mongoose.Schema({
        child: { 'name' : String, 'age' : Number }  // not an array, just a sub document
    });
    var Parent = mongoose.model('Parent', parentSchema);

    var parent = new Parent();
    parent.child.name = "Joe";
    parent.child.age  = 13;

    parent.save(function(err, saved) {
        if(err) console.error(err);
    });

这篇关于猫鼬:如何插入单个子文档-不是数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆