【问题标题】:How do you refresh the data in a mongoose document that has already been loaded?如何刷新已经加载的 mongoose 文档中的数据?
【发布时间】:2012-08-30 21:48:02
【问题描述】:

要明确这个问题与从数据库加载数据有关,而不是更新数据库中的文档。

使用以下架构:

new mongoose.Schema
  name: String
  code:
    type: String
    index:
      unique: true
  _contacts: [
    type: mongoose.Schema.Types.ObjectId
    ref: 'Person'
  ]

我已经像这样创建了我的文档:

client = new Client code:'test',name:'test competition',contacts:[]
client.save()

在应用程序的其他地方或通过 API 调用,它不能轻易引用上面缓存的版本:

Client.findOne(code:'test').exec (err,client) ->
  return if err or not client
  client._contacts.push person.id # person has come from somewhere
  client.save (err) ->
    return err if err

如果我们返回到我们原来的 client 对象,我想知道是否有办法为整个文档或仅针对特定路径刷新该对象。比如;

client.refresh '_contacts', (err) ->
  return err if err

或者最好只维护一个全局引用的对象?

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    最好的做法是只保留像 client 这样的 Mongoose 模型实例,只要您积极使用它,正是因为它很容易与数据库中的内容不同步。在需要时使用findOne 重新创建您的client 对象,而不是尝试刷新可能过时的副本。

    【讨论】:

      猜你喜欢
      • 2015-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-01
      • 2020-01-17
      • 2015-04-12
      • 2014-11-03
      • 2021-12-16
      相关资源
      最近更新 更多