To be clear this question relates to loading data from the database, not updating documents in the database.
With the following schema:
new mongoose.Schema
name: String
code:
type: String
index:
unique: true
_contacts: [
type: mongoose.Schema.Types.ObjectId
ref: 'Person'
]
I've created my document like so:
client = new Client code:'test',name:'test competition',contacts:[]
client.save()
Elsewhere in the application or via an API call, somewhere that it can't easily refer to 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 return to our original client object what I would like to know is if there's a way to refresh that object either for the whole document or just a particular path. For instance;
client.refresh '_contacts', (err) ->
return err if err
Or would it be better practice to maintain only one object that is referred to globally?
The save() function is generally the right way to update a document with Mongoose. With save() , you get full validation and middleware. For cases when save() isn't flexible enough, Mongoose lets you create your own MongoDB updates with casting, middleware, and limited validation.
Upsert is a combination of insert and update (inSERT + UPdate = upsert). We can use the upsert with different update methods, i.e., update, findAndModify, and replaceOne. Here in MongoDB, the upsert option is a Boolean value. Suppose the value is true and the documents match the specified query filter.
As the name implies, findOneAndUpdate() finds the first document that matches a given filter , applies an update , and returns the document. By default, findOneAndUpdate() returns the document as it was before update was applied. You should set the new option to true to return the document after update was applied.
Best practice is to only keep a Mongoose model instance like client
around as long as you're actively using it, precisely because it can so easily become out of sync with what's in the database. Recreate your client
object whenever you need it using findOne
instead of trying to refresh potentially stale copies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With