【发布时间】: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。
为什么当我将附加到父对象的对象独立保存在代码的其他位置时,它没有得到更新?
【问题讨论】: