【问题标题】:Possible circular reference in mongoose猫鼬中可能的循环引用
【发布时间】:2016-11-06 11:43:53
【问题描述】:

当我需要保存“文档”时,我遇到了循环依赖问题。

我的应用程序都是通过 AngularJS 接口的 Restfull。

在创建公司的屏幕上,您可以创建对象和服务。在创建SERVICES屏幕时,必须关联一个已创建的OBJECT。

问题是创建的 OBJECT 还没有持久化,所以我没有 _id。 因此无法在 SERVICE 中引用它。只有当我有一个 OBJECT 持久化时,我才能将它关联到 company.services[0].object

有什么建议吗?

这是我需要保存在 MongoDB 中的。查看 SERVICE 中对 OBJECT "5779f75a27f9d259248211c7" 的引用。

/* 1 */
{
    "_id" : ObjectId("5749bb92bf8145c97988e4a9"),
    "name" : "company 1",
    "services" : [
        {
            "_id" : ObjectId("5764cb2c00d00cf10c9c41c6"),
            "description" : "service 1",
            "object" : ObjectId("5779f75a27f9d259248211c7"),
        }
    ],
    "objects" : [
        {
            "_id" : ObjectId("5779f75a27f9d259248211c7"),
            "description" : "object 1",
        }
    ]
}

这是我的架构:

var objectSchema = new mongoose.Schema({
  description: {
    type: String,
    trim: true,
    unique: true,
    required: 'Description is required'
  }
})

var serviceSchema = new mongoose.Schema({
  description: {
    type: String,
    trim: true,
    required: 'Description is required'
  },
  object: {
    type: mongoose.Schema.ObjectId,
    ref: 'Object'
  },
})

var companySchema = new mongoose.Schema({
  name: {
    type: String,
    default: '',
    trim: true,
    unique: true,
    required: 'Name is required'
  },
  guarda_documentos: {
    services: [serviceSchema],
    objects: [objectSchema],
  },
});

mongoose.model('Company', companySchema);
mongoose.model('Object', objectSchema);

【问题讨论】:

    标签: angularjs node.js mongodb mongoose


    【解决方案1】:

    您需要先持久化您的对象,一旦完成,使用返回的_id 来持久化您的服务。这是一个异步进程。

    // Simplified code concept
    
    // Create a new object
    var o = new Object()
    o.description = 'foo'
    ...
    
    // Create a new service
    var s = new Service()
    
    // Save object and return it (will now have an _id)
    o.save(function(err, doc) {
    
      // Add object reference to service and save
      s.object = doc._id
      s.save(function(err, res) {
        // Call your controller or whatever callback here
      })
    }) 
    

    另一方面,不要使用“对象”作为您的文档名称。它已经在 J​​avascript 中定义。

    【讨论】:

    • 问题是Service和Object是Company的子文档。
    • 既然您的对象是服务中的引用,为什么要将它作为公司的子文档。除非它有其他目的然后在此处描述,否则请从公司中删除对象子文档。然后按照同样的async流程:对象保存->服务保存->公司保存
    猜你喜欢
    • 2014-01-28
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-01
    • 2019-11-10
    相关资源
    最近更新 更多