Is there a way to store a document then get an updated value of it at a later date without needing to query and populate again?
const someDocument = await SomeModel.findOne({...}).populate(...);
// store a reference to it for use
const props = {
document: someDocument,
...
}
// at a later time
await props.document.getLatest() <-- update and populate in place?
CodePudding user response:
As describe here, You can define your own custom document instance methods by add functions on the schema level.
example taken from mongoose doc:
// define a schema
const animalSchema = new Schema({ name: String, type: String });
// assign a function to the "methods" object of our animalSchema
animalSchema.methods.findSimilarTypes = function(cb) {
return mongoose.model('Animal').find({ type: this.type }, cb);
};
const Animal = mongoose.model('Animal', animalSchema);
const dog = new Animal({ type: 'dog' });
dog.findSimilarTypes((err, dogs) => {
console.log(dogs); // woof
});
This is the only way I can think of doing what you want - add a function that populate.
another thing that might help: you can create a pre hook on 'find' and add populate in it