我正在尝试使用 push()
方法将子文档推送到父文档中。
之后,我想保存调用 save()
方法的父文档。但结果是一个空数组。
我也曾尝试在保存父文档之前调用 parent.markModified('children')
,但这没有任何区别。
下面是我的模式和应该保存子文档的代码:
架构:
const profileSessionSchema = mongoose.Schema({
firstName: { type: String, trim:true},
...
realisations : [realisationSchema],
});
ProfileSession = mongoose.model('ProfileSession',profileSessionSchema);
const realisationSchema = mongoose.Schema({
profileId :{ type: mongoose.Schema.Types.ObjectId, ref: 'ProfileSession'},
...
type : { type: String, enum:conf.wallTypes, required:true, default:'classic'},
});
Realisation = mongoose.model('Realisation', realisationSchema);
ProfileSession.create(profileData,function(err,profile){
for(j=0;j<realisations.length;j++){ // realisations array is not empty
var r = Realisation(realisations[j])
r.save(function(a,real){
profile.realisations.push(real)
})
}
profile.markModified('realisations')
profile.save()
})
配置文件确实是在数据库中创建的,但没有实现子文件。我发现了很多关于此的主题,看来方法 markModified
应该可以解决这个问题。但这不是我的情况,我不明白为什么......
谢谢你的帮助。 干杯
最佳答案
我认为您的 for 循环迭代速度太快,r.save() 无法完成,然后在实际保存之前调用 profile.save()。也许把一些 console.log 放在你的 r.save() 里面,然后放在你的 profile.save() 上面,这样你就可以看到每个调用的顺序
关于node.js - mongoose - 子文档数组未保存在父文档中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56364848/