[英]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:示例取自 mongoose 文档:
// 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.这是我能想到做你想做的唯一方法 - 添加一个填充的 function。
another thing that might help: you can create a pre hook on 'find' and add populate in it另一件可能有帮助的事情:您可以在“查找”上创建一个预挂钩并在其中添加填充
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.