node.js - mongoose - 子文档数组未保存在父文档中

标签 node.js mongodb mongoose

我正在尝试使用 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/

相关文章:

javascript - 用于 Node js 的 c++ v8 异步模块,与结构中的类型相关的错误

node.js - 使用获取 MongoError 的 Node 连接到 mongo 容器

node.js - 在 4 个集合之间进行 $Lookup,其中 3 个具有 ObjectId,第 4 个是 String,生成空数组

node.js - Karma 出现 ReferenceError : Can't find variable: module on the karma config file itself 错误

node.js - 在 IntelliJ 中调试 Node.js Bot Builder 项目

javascript - 部署 Meteor : Error: spawn ENOENT at errnoException (child_process. js:988:11)

node.js - 限制数组字段的查询结果

mongodb - 如何向当前日期字段添加天数以便能够比较日期范围

javascript - Mongoose 在发布数据后复制条目

node.js - 如何在我的 Node 应用程序中使用 --harmony 标志与 phusion乘客?