Mongo/Mongoose JS — 将文档更新到最新状态?
Mongo/Mongoose JS — Update document to latest state?
有没有办法存储一个文档,然后在以后获取它的更新值而不需要再次查询和填充?
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?
如描述here,
您可以通过在架构级别添加函数来定义自己的自定义文档实例方法。
取自 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
});
这是我能想到的做你想做的唯一方法 - 添加一个填充函数。
另一件可能有帮助的事情:您可以在 'find' 上创建一个预挂钩并在其中添加填充
有没有办法存储一个文档,然后在以后获取它的更新值而不需要再次查询和填充?
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?
如描述here, 您可以通过在架构级别添加函数来定义自己的自定义文档实例方法。
取自 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
});
这是我能想到的做你想做的唯一方法 - 添加一个填充函数。
另一件可能有帮助的事情:您可以在 'find' 上创建一个预挂钩并在其中添加填充