我有两个模式,一个“项目”模式和一个“应用程序”模式。
在集合中创建新条目并根据新条目内的数据更新另一个集合中的现有条目的最有效方法是什么?当Applications集合发生变化时,我是否可以避免发出多个API请求并以某种方式在mongoDB端运行“存储过程”来处理Projects集合的更新?
在这种情况下,理想情况下,当创建项目的应用程序时,将在Applications集合中创建一个新条目,并更新Projects集合中的Project以反映应用程序中的信息。
我可以在不发出多个api请求的情况下执行此操作吗?
项目架构:
// models product.js
const mongoose = require('mongoose');
const { ObjectId } = mongoose.Schema;
const projectSchema = new mongoose.Schema({
name: {
type: String,
trim: true,
required: true,
maxlength: 32
},
applications: {
type: Number,
default: 0
},
created_by: {
type: ObjectId,
ref: 'User'
},
applicants: {
type: Array,
default: []
}
}, {timestamps: true}
);
module.exports = mongoose.model("Project", projectSchema);
应用架构:
const mongoose = require('mongoose');
const applicationSchema = new mongoose.Schema({
applicantId: {
type: ObjectId,
ref: 'User'
},
ownerId: {
type: ObjectId,
ref: 'User'
},
projectId: {
type: ObjectId,
ref: 'Project'
}
}, {timestamps: true});
module.exports = mongoose.model("Application", applicationSchema);
请注意,这些是独立的架构,因为它们每个都包含15个字段,因此我将其精简以发布此问题。
答案 0 :(得分:0)
我建议将钩子用于猫鼬模型,有一个后保存钩子,您可以在应用程序模型上使用它来更新项目并增加应用程序计数。
编辑-添加了伪代码
// models -> project.js
const mongoose = require('mongoose');
const {
ObjectId
} = mongoose.Schema;
const projectSchema = new mongoose.Schema({
name: {
type: String,
trim: true,
required: true,
maxlength: 32
},
applications: {
type: Number,
default: 0
},
created_by: {
type: ObjectId,
ref: 'User'
},
applicants: {
type: Array,
default: []
}
}, {
timestamps: true
});
projectSchema.statics = {
/**
* Find project by _id
*
* @param {ObjectId} _id
* @api private
*/
get: function (_id) {
return this.findOne({
_id
})
.exec();
}
}
module.exports = mongoose.model("Project", projectSchema);
const mongoose = require('mongoose');
const projectModel = require("./project")
const applicationSchema = new mongoose.Schema({
applicantId: {
type: ObjectId,
ref: 'User'
},
ownerId: {
type: ObjectId,
ref: 'User'
},
projectId: {
type: ObjectId,
ref: 'Project'
}
}, {
timestamps: true
});
// Async hook
applicationSchema.post('save', function (doc, next) {
const relatedProject = projectModel.get(doc.projectId);
relatedProject.applications++;
relatedProject.save();
next();
});
module.exports = mongoose.model("Application", applicationSchema);