如何在 Azure 函数应用中的文件之间共享代码(例如 Mongo 架构定义)?
我需要这样做,因为我的函数需要访问共享的 mongo 架构和模型,例如这个基本示例:
var blogPostSchema = new mongoose.Schema({
id: 'number',
title: 'string',
date: 'date',
content: 'string'
});
var BlogPost = mongoose.model('BlogPost', blogPostSchema);
我尝试添加一个"watchDirectories": [ "Shared" ]
线路到我的host.json
并在该文件夹中添加了一个index.js
包含上述变量定义,但这似乎不适用于其他函数。
我只是得到一个Exception while executing function: Functions.GetBlogPosts. mscorlib: ReferenceError: BlogPost is not defined
.
我也尝试过明确require
ing .js 文件,但这似乎没有找到。可能是我刚刚走错了路。
有谁有关于如何分享的示例或提示.js
天蓝色函数之间的代码?
我通过执行以下步骤修复了此问题:
- 向根添加一行
hosts.json
to watch
共享文件夹。"watchDirectories": [ "Shared" ]
- 在共享文件夹中添加一个
blogPostModel.js
包含以下模式/模型定义和导出的文件
共享\blogPostModel.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var blogPostSchema = new Schema({
id: 'number',
title: 'string',
date: 'date',
content: 'string'
});
module.exports = mongoose.model('BlogPost', blogPostSchema);
- 在我的函数中
require
具有以下路径的共享文件:var blogPostModel = require('../Shared/blogPostModel.js');
然后我可以建立连接并与模型进行交互find
每个单独的函数中的 s 等。
该解决方案由以下 SO 帖子组成:
Node.js 中的 Azure Function 和共享文件
编译 Mongoose 后无法覆盖模型
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)