我目前正在构建一个简单的nestjs 模块。我通读了文档并基本上遵循了他们的建议。但由于某种原因,当我将 Mongoose 架构引入服务时,Nest JS 无法解析我当前正在开发的模块。
目前的设置非常简单,我在根应用程序模块中打开两个数据库连接,并且只导入一个名为“private”的模块。
另一方面,私有模块导入的模块(属性)给我带来了问题。
这里出现了奇怪的部分:在服务文件(PropertiesService)中注释掉与模式相关的逻辑时,一切都可以正常编译,但是当取消注释时,我收到此错误:
2024-03-08 23:07:46 [Nest] 545 - 03/08/2024, 10:07:46 PM ERROR [ExceptionHandler] Nest can't resolve dependencies of the PropertiesService (?). Please make sure that the argument "PropertyModel" at index [0] is available in the PropertiesModule context.
因此,当服务使用这样的模式时:
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import {
Property,
PropertyDocument,
} from 'src/private/properties/properties.schema';
@Injectable()
export class PropertiesService {
constructor(
@InjectModel(Property.name)
private propertyModel: Model<PropertyDocument>,
) {}
createProperty() {
const myTestObject = new this.propertyModel({ name: 'MyTestString' });
return myTestObject.save();
}
getPropertyCollection() {
return 'myCollection';
}
updateProperty() {}
deleteProperty() {}
}
会抛出上面的错误。
但是当我注释掉相关逻辑时,它会编译...
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import {
Property,
PropertyDocument,
} from 'src/private/properties/properties.schema';
@Injectable()
export class PropertiesService {
// constructor(
// @InjectModel(Property.name)
// private propertyModel: Model<PropertyDocument>,
// ) {}
createProperty() {
// const myTestObject = new this.propertyModel({ name: 'MyTestString' });
// return myTestObject.save();
}
getPropertyCollection() {
return 'myCollection';
}
updateProperty() {}
deleteProperty() {}
}
所以看来问题一定出在这里,但我无法弄清楚为什么/这里出了什么问题。另请注意,虽然 PropertiesService 当时没有使用架构,但 PropertyModule 仍在使用它们,所以我很确定错误一定在这个服务文件中......其余的代码:
https://github.com/Samulsen/PRO-datc-server/tree/DevCommit_PropertiesApi
首先,我用头撞墙好几次,开始思考我是否应该成为一名农民。
除了通常的过程之外,我通读了这里的文档,其中使用 cats API 展示了这个非常简单的示例:https://docs.nestjs.com/techniques/mongodb。
我试图通过 ChatGPT / Copilot 解决这个问题,但他似乎在度假什么的,他只说些废话...
这是我第二次夜班试图解决这个问题,我只是累了,希望得到帮助。这可能是一些愚蠢的初学者问题...
因为您使用命名数据库(通过检查存储库发现这一点),所以您还需要在
@InjectModel()
中使用该名称作为第二个参数。这是由于 Nest 如何跨多个数据库跟踪注入令牌,因此它知道要注入哪一个。您的 @InjectModel()
应类似于 @InejctModel(Property.name, 'dictDB')