【问题标题】:Mongo/Mongoose JS — Update document to latest state?Mongo/Mongoose JS — 将文档更新到最新状态?
【发布时间】:2022-02-22 21:46:18
【问题描述】:

有没有一种方法可以存储文档,然后在以后获取它的更新值,而无需再次查询和填充?

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?

【问题讨论】:

    标签: javascript mongoose


    【解决方案1】:

    here 所述, 您可以通过在架构级别添加函数来定义自己的自定义文档实例方法。

    示例取自猫鼬文档:

     // 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
     });
    

    这是我能想到的唯一方法 - 添加一个填充函数。

    另一件事可能会有所帮助:您可以在“查找”上创建一个预挂钩并在其中添加填充

    【讨论】:

    • 我是这么想的,谢谢确认
    猜你喜欢
    • 2018-12-22
    • 2021-04-23
    • 1970-01-01
    • 2018-06-19
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多