【问题标题】:Sub-document saving is not updating parent子文档保存不更新父
【发布时间】:2014-03-06 05:33:54
【问题描述】:

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

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

但是,我现在遇到了一点不同步的问题。父对象上有单个子对象,但仅填充名称和一些特定于猫鼬的信息 (objectId)。还创建了一个子表,其中子信息已完全填充,并且它具有与附加到父级的子级相同的 objectID。

为什么当我将附加到父对象的对象独立保存在代码的其他位置时,它没有得到更新?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案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.
    
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-18
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      • 2015-08-18
      • 2020-02-26
      • 2016-03-22
      • 2013-06-06
      相关资源
      最近更新 更多