如何刷新已加载的mongoose文档中的数据?

chr*_*gan 8 mongoose mongodb

要明确这个问题涉及从数据库加载数据,而不是更新数据库中的文档.

使用以下架构:

new mongoose.Schema
  name: String
  code:
    type: String
    index:
      unique: true
  _contacts: [
    type: mongoose.Schema.Types.ObjectId
    ref: 'Person'
  ]
Run Code Online (Sandbox Code Playgroud)

我已经创建了我的文档:

client = new Client code:'test',name:'test competition',contacts:[]
client.save()
Run Code Online (Sandbox Code Playgroud)

在应用程序的其他地方或通过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
Run Code Online (Sandbox Code Playgroud)

如果我们返回到我们原始的客户端对象,我想知道的是,是否有办法为整个文档或只是特定路径刷新该对象.例如;

client.refresh '_contacts', (err) ->
  return err if err
Run Code Online (Sandbox Code Playgroud)

或者更好的做法是只维护一个全局引用的对象?

Joh*_*yHK 8

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