Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js mongoose:如何插入单个子文档-而不是数组_Node.js_Mongodb_Mongoose - Fatal编程技术网

Node.js mongoose:如何插入单个子文档-而不是数组

Node.js mongoose:如何插入单个子文档-而不是数组,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,在mongoose中,您可以根据以下内容声明子文档的架构: var childSchema = new mongoose.Schema({ name: String, age: String }); var parentSchema = new mongoose.Schema({ children: [childSchema] }); var Parent = mongoose.model('Parent',

在mongoose中,您可以根据以下内容声明子文档的架构:

        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);
        });
似乎子文档类型需要是数组。我需要能够将子文档保存为单个实例,而不是数组,即:

        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);
        });
因此,不是数组或引用,而是单个实例子文档。这可能吗?如果不是,我应该使用:

var childInstance = child.toObject();
哎呀!编辑: 我完全误解了你的问题。。那么您想存储一个子文档?那么为什么将属性命名为
children

您可以使用:

var ParentSchema    =   new schema({
    name : String,
    child: Object
});

// etc.

john.child = new Child({name: 'kiki'});
// which is actually the same as: john.child = {name:'kiki'};
john.save();
通过这种方式,mongoose将文档转换为简单对象并存储它。但我不认为这样做有什么用?它没有模式的优点,而是用作默认对象。不将其放入数组也会阻止您添加更多嵌套项

旧的: 您不需要将子模式直接注入父模式,而需要首先链接它们(并且您想单独存储它们,对吗?)

因此我们得到了两个集合:
父集合
子集合
(=
父集合
&&
子集合
)。集合
子集合的所有文档都链接到特定的
父集合。并且一个
父级
文档链接了零个、一个或多个
子级
文档

通过这种方式,您可以保持修改模式的能力(如附加
方法
静态
),并将文档整齐地分开,您可以获得想要的“子”效果:

//  get mongoose.
var mongoose = require('mongoose');

//  connect to your local pc on database myDB.
mongoose.connect('mongodb://localhost:27017/myDB');

//  parent schema.
var parentSchema = new mongoose.Schema({
  name     : String,
  //  the ObjectId's of the children links the two schema's.
  children   : [{type:mongoose.Schema.Types.ObjectId, ref:'Child'}]
});

//  child schema.
var childSchema = new mongoose.Schema({
  name   : String,
  //  the parent's ObjectId links to the owner.
  parent : {type:mongoose.Schema.Types.ObjectId, ref:'Parent'}
});

//  model the schema's.
var Child   = mongoose.model('Child', childSchema),
    Parent  = mongoose.model('Parent', parentSchema);

//  create a 'parent'.
//  we are not assigning the children yet.
var john     = new Parent({name:'John'});

//  create two children and save them. Link them to john.
var child1   = new Child({name:'Mimi', parent:john._id}),
    child2   = new Child({name:'Kiki', parent:john._id});

//  push child to children property of john.
john.children.push(child1);
john.children.push(child2);

//  save everything.
john.save();
child1.save();
child2.save();
这将返回以下内容:

/**
Children: 
[ { name: 'Mimi',                                                                                                                                                                                                                            
    parent: 537258f63eb92b3201b65e56,                                                                                                                                                                                                        
    _id: 537258f63eb92b3201b65e57,                                                                                                                                                                                                           
    __v: 0 },                                                                                                                                                                                                                                
  { name: 'Kiki',                                                                                                                                                                                                                            
    parent: 537258f63eb92b3201b65e56,                                                                                                                                                                                                        
    _id: 537258f63eb92b3201b65e58,                                                                                                                                                                                                           
    __v: 0 } ]

Parent:
[ { name: 'John',                                                                                                                                                                                                                            
    _id: 537258f63eb92b3201b65e56,                                                                                                                                                                                                           
    __v: 0,                                                                                                                                                                                                                                  
    children: [ 537258f63eb92b3201b65e57, 537258f63eb92b3201b65e58 ] } ]
*/
您还可以为collection
parents
addChild(child,callback)
,使代码看起来更干净(javaísh风格)

伪代码:

// add custom static method.
parentSchema.statics.addChild = function(child, callback) {
   // implementation.
}

// the way you call this method:
parentModel.addChild(new Child.etc..);

希望这对您有所帮助,祝您好运(:

有时很难看出明显的问题。您不需要另一个架构来实现所需的功能。您只需在父架构中定义子文档,如下所示:

    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);
    });

如果两个集合的关系为1对1。 您可以使用“ref”

var personSchema = Schema({
  _id     : Number,
  name    : String,
  age     : Number,
  stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

var storySchema = Schema({
  _creator : { type: Number, ref: 'Person' },
  title    : String,
  fans     : [{ type: Number, ref: 'Person' }]
});

来源:

如果父级有数百个子级,而我不想使用数组(出于性能原因),我可以看到这种方法的优点。这种方法的缺点是没有对子级运行验证…请参阅