子文档保存不会更新父文件

时间:2014-02-08 19:41:36

标签: node.js mongodb mongoose

我正在尝试学习猫鼬的一些关系机制。我有两个模特,父母和孩子:

var childrenSchema = new Schema({
    name : String,
    date : {type : Date, default: Date.now},
    attribute1 : String,
    attribute2 : String,
})


var parentSchema = new Schema({
    name: String,
    children: [childrenSchema]
})

exports.parent = mongoose.model('Parent', parentSchema);
exports.children = mongoose.model('Person', childrenSchema);

我将在初始调用中创建父对象,并向api发送异步调用,该api根据子名称获取子信息。当异步调用结束时,我按原样返回父节点,因为用户不需要立即查看子节点的信息。

var Parent = require('schema.js').parent;
var Child= require('schema.js').children;

function addParent(p){
    var parent = new Parent();
    parent.name = p.result.name;
    var child = new Child();
    child.name = p.result.childname;
    parent.children.push(child);
    getChildDetails(child); // Async function to get children info..
    parent.save(); //Save the parent so the information we return is persisted.
    return parent; //Children probably not fully populated here. Not a problem.
}

function getChildDetails(child){
    var promiseapi = require('mypromiseapi');
    promiseapi.fetch('childinfo',child.name).then(function(result){
        child.attribute1 = result.attribute1;
        child.attribute2 = result.attribute2;
    }).then( function(){
        child.save(); // I expect the parent's information to be updated.
    });
}

但是,我现在处于一个不同寻常的问题。父对象上有单个子对象,但只填充名称和一些mongoose特定信息(objectId)。还会创建子表,子信息已完全填充,并且它与附加到父项的子项具有相同的objectID。

当我在代码中的其他地方独立保存时,为什么附加到父级的对象不会更新?

1 个答案:

答案 0 :(得分:1)

我通过使用Populations(http://mongoosejs.com/docs/populate.html)而不是纯模式来解决它。新的模式模型如下所示:

var childrenSchema = new Schema({
    name : String,
    date : {type : Date, default: Date.now},
    attribute1 : String,
    attribute2 : String,
})


var parentSchema = new Schema({
    name: String,
    children: [{type: Schema.Types.ObjectId, ref:'Child'}]
})

新的addParent方法如下所示:

function addParent(p){
    var parent = new Parent();
    parent.name = p.result.name;
    var child = new Child();
    child.name = p.result.childname;
    parent.children.push(child._id);
    child.save();
    getChildDetails(child); // Async function to get children info..
    parent.save(function(err,result){
        Parent.populate(result,{path:'children'},function(err,resultparent){
            return(result);
        });
    }); //Save the parent so the information we return is persisted.

}