How do you update data in a previously uploaded mongoose document?

To be clear, this issue is related to loading data from the database, not updating documents in the database.

With the following diagram:

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

I created my document as follows:

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

Elsewhere in the application or through an API call, somewhere that it cannot easily reference the version cached above:

 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 

If we go back to our original client object, I would like to know if there is a way to update this object either for the entire document, or only for a specific path. For example,

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

Or would it be better to support only one object, which is called globally?

+7
source share
1 answer

It’s best practice to save an instance of the Mongoose model, such as client , while you are actively using it, precisely because it can so easily stop synchronizing with what's in the database. Recreate your client object when you need it, using findOne instead of updating potentially obsolete copies.

+8
source

All Articles