piz*_*r0b 4 mongoose mongodb node.js
我正在为一个网站创建一个 CMS。有一个关于页面需要包含来自 CMS 的内容。只需要一个文档作为关于页面的配置文件。我为此提出的解决方案是:
有一个更好的方法吗?有没有办法在save
我的架构的预挂钩中执行此操作?
可以为单例模型做这样的事情:
HomePageSchema.statics = {
getSingleton: function (cb) {
this.findOne()
.sort({updated: -1})
.limit(1)
.exec(function (error, model) {
if (error) {
cb(error, null);
} else if (model == null) {
cb(error, new HomePage());
} else {
cb(error, model);
}
});
},
};
Run Code Online (Sandbox Code Playgroud)
进而
HomePage.getSingleton((err, homepage) => {
homepage.image = '/images/myImage.jpg';
homepage.headline = 'Homepage Headline';
homepage.save();
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2871 次 |
最近记录: |