我使用打字稿开发了nodejs项目。而且我不明白为什么以下代码无法正常工作。 这里我们有A.ts,B.ts和index.ts。
// A.ts
import * as mongoose from 'mongoose';
import {Bmodel} from './B';
const schema = new mongoose.Schema({
name: {
type: String,
required: true
},
B: [{
type : mongoose.Types.ObjectId,
ref : Bmodel.modelName
}]
});
export const Amodel = mongoose.model('A',schema);
// B.ts
import * as mongoose from 'mongoose';
import {Amodel} from './A';
const schema = new mongoose.Schema({
name: {
type: String,
required: true
},
A: [{
type : mongoose.Types.ObjectId,
ref : Amodel.modelName
}]
})
export const Bmodel = mongoose.model('B',schema);
import * as mongoose from 'mongoose';
import "./A";
import './B';
mongoose.connect("mongodb://localhost/movies")
.then(()=>{
console.log("db connected!");
})
.catch((err)=>{
console.log(err);
})
在package.json中
{
"name": "testlab",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"devDependencies": {
"@types/mongoose": "^5.5.34"
},
"dependencies": {
"mongoose": "^5.8.2"
}
}
通过命令“ tsc index.ts”编译上面的代码后,我们得到了js文件。运行“ node index.js”时,它将引发以下错误:
/mnt/e/Project/Express-blueprint-ts/testlab/B.js:12
ref: A_1.Amodel.modelName
^
TypeError: Cannot read property 'modelName' of undefined
at Object.<anonymous> (/mnt/e/Project/Express-blueprint-ts/testlab/B.js:12:29)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/mnt/e/Project/Express-blueprint-ts/testlab/A.js:4:11)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)