javascript – bluebird Promisies crud示例使用nodejs,express和mongoose

前端之家收集整理的这篇文章主要介绍了javascript – bluebird Promisies crud示例使用nodejs,express和mongoose前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的朋友,不幸的是我找不到任何关于如何在节点js express mongoose app中实现bluebird promise库的例子.

我的应用程序设置为猫鼬模型,控制器和路由在不同的文件中.

但是用mongoose实现它,我只是无法弄明白.

所以请有人告诉我它是如何使用的.请看下面.

  1. //express controller Article.js
  2.  
  3.  
  4. var mongoose = require('mongoose'),errorHandler = require('./errors'),Article = mongoose.model('Article');
  5.  
  6. exports.list = function(req,res) {
  7. Article.find().sort('-created').populate('user','displayName').exec(function(err,articles) {
  8. if (err) {
  9. return res.status(400).send({
  10. message: errorHandler.getErrorMessage(err)
  11. });
  12. } else {
  13. res.jsonp(articles);
  14. }
  15. });
  16. };

//猫鼬模型

  1. /**
  2. * Module dependencies.
  3. */
  4. var mongoose = require('mongoose'),Schema = mongoose.Schema;
  5.  
  6. /**
  7. * Article Schema
  8. */
  9. var ArticleSchema = new Schema({
  10. created: {
  11. type: Date,default: Date.now
  12. },title: {
  13. type: String,default: '',trim: true,required: 'Title cannot be blank'
  14. },content: {
  15. type: String,trim: true
  16. },user: {
  17. type: Schema.ObjectId,ref: 'User'
  18. }
  19. });
  20.  
  21. mongoose.model('Article',ArticleSchema);

所以,如果我想使用Bluebird promise库,我将如何更改export.list

提前致谢.

一些问题,

我在哪里可以在猫鼬模型上调用promisify?
例如Article = mongoose.model(‘Article’);
喜欢thisArticle = Promise.promisifyAll(require(‘Article’));
要么
像这样

  1. var Article = mongoose.model('Article');
  2. Article = Promise.promisifyAll(Article);

解决方法

好几个星期在互联网上搜索后,我找到了一个例子 here
为了在nodejs app中使用mongoose模型,

你需要像这样宣传图书馆和模型实例
在定义架构后,在模型模块中

  1. var Article = mongoose.model('Article',ArticleSchema);
  2. Promise.promisifyAll(Article);
  3. Promise.promisifyAll(Article.prototype);
  4.  
  5. exports.Article = Article;
  6. //Replace Article with the name of your Model.

现在你可以像你一样在你的控制器中使用你的mongoose模型

  1. exports.create = function(req,res) {
  2. var article = new Article(req.body);
  3. article.user = req.user;
  4.  
  5. article.saveAsync().then(function(){
  6. res.jsonp(article);
  7. }).catch(function (e){
  8. return res.status(400).send({
  9. message: errorHandler.getErrorMessage(e)
  10. });
  11. });
  12. };

猜你在找的JavaScript相关文章