为了操作我的mongoose-Schemas,我喜欢创建静态方法,但我必须承认,这是我第一次尝试启动并运行MEAN-stack-backend。前端和快速路由工作正常,因此我们首先关注架构:
// tracking.model.ts
import mongoose from 'mongoose';
var Schema = mongoose.Schema;
var TrackingModuleSchema = new Schema ({
// internal _id
modulename : { type: String, required:true,unique:true },
});
TrackingModuleSchema.statics.myFindByName= function (name,cb) {
return this.findOne( {name:new RegExp(name,'i')},cb);
};
TrackingModuleSchema.statics.myFindOrCreate = function (name,cb) {
this.myFindByName(name,function(err,modules) {
console.error(err);
console.log(modules);
cb(err,modules); // TODO return module._id....
});
};
// Create a `schema` for the Tracking object
var TrackingSchema = new Schema({
// _id internal.
timestamp: {type: Date },
sequence : { type: Number },
module: { type: Schema.Types.ObjectId, ref: 'TrackingModule' },
severity: { type: String},
action: { type: String },
from: { type: String },
to: { type: String },
});
// removed some code (Static methods to TrackingSchema)...
// create schema objects
var TrackingModule = mongoose.model('TrackingModule',TrackingModuleSchema);
var Tracking = mongoose.model('Tracking',TrackingSchema);
// module.exports all objects...
module.exports = function ( ) {
return {
TrackingModule : TrackingModule ,
Tracking : Tracking,
};
}
现在是路由,其中导入并使用了模式:
const express = require('express');
const router = express.Router();
import {Tracking,TrackingModule} from '../models/tracking.model';
router.get('/module', (req,res) => {
var moduleName = '';
if (req.query.moduleName) {
moduleName = req.query.moduleName;
} else {
console.log('Empty tracking-moduleName');
res.send(500);
return;
}
// the error happens in the following line:
TrackingModule.myFindOrCreate(moduleName,function(err,msgId){
if (err) {
console.error(err); // errors with tracking ->console...
res.send(500);
} else {
res.json( msgList );
}
});
});
// removed code for other gets and posts, not releveant to the error.
module.exports = router;
即使我尝试重命名静态函数的名称,也会出现错误TypeError: Cannot read property 'myFindOrCreate' of undefined
。是的,我还没有完成myFindOrCreate的实现。
在此之前导入无法识别,因此我在this instruction之后安装了babel-cli 6.23.0。我使用了 package.json 中的start-skript:
"scripts": {
"ng": "ng",
"start": "ng serve",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"starts": "nodemon server/server.js --watch server --exec babel-node",
"builds": "babel lib -d server.dist",
"serve": "node server.dist/server.js",
"tests": "mocha --compilers js:babel-register"
},
然而,构建,服务和测试我也没有设法工作,我稍后会检查。现在我已经检查了所有"类似问题"在问题编辑器的右侧以及可能已经有你的答案的所有问题"在这个编辑器之上,没有任何帮助。
答案 0 :(得分:1)
在tracking.model.ts
文件中,而不是:
module.exports = function() {
return {
TrackingModule: TrackingModule,
Tracking: Tracking,
};
}
使用export
关键字,如下所示:
export const TrackingModule = TrackingModule;
export const Tracking = Tracking;
您无法将较旧的module.exports
模式与ES6 export-import
模式混淆。它们的处理方式不同。