简体   繁体   中英

Mongo/Mongoose JS — Update document to latest state?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM