我有一个非常基本的feess服务,它使用feathers-mongoose包将数据存储在mongoose中。问题在于获取功能。我的模型如下:
module.exports = function (app) {
const mongooseClient = app.get('mongooseClient');
const { Schema } = mongooseClient;
const messages = new Schema({
message: { type: String, required: true }
}, {
timestamps: true
});
return mongooseClient.model('messages', messages);
};
当用户运行 GET 命令时:
curl http://localhost:3030/messages/test
我有以下要求
- 这实际上是尝试将测试转换为 ObjectID。我会做什么 喜欢做的是针对消息属性运行查询 {message : "test"} ,我不知道如何实现这一点。有 没有足够的文档来理解编写或更改此内容 在钩子(Hook)里。有人可以帮忙吗
- 当未找到行或与我的某些条件不匹配时,我想返回自定义错误代码 (http)。我怎样才能实现这个目标?
谢谢
最佳答案
羽毛 before hook您可以设置context.result在这种情况下,将跳过原始数据库调用。所以流程是
- 在 before
get
Hook 中,尝试按名称查找消息 - 如果存在,请将
context.result
设置为找到的内容 - 否则不执行任何操作,将通过 id 返回原始
get
它看起来是这样的:
async context => {
const messages = context.service.find({
...context.params,
query: {
$limit: 1,
name: context.id
}
});
if (messages.total > 0) {
context.result = messages.data[0];
}
return context;
}
如何创建自定义错误并设置错误代码记录在 Errors API 中.
关于javascript - 羽毛- Mongoose : Get by custom attribute in feathers-mongoose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57402993/