书籍 Controller
我希望数据按 postman 中的名称显示,而不是 ID,因为我有信息,并且我想通过数据库中的名称获取它
const getByName = async (req, res, next) => {
const name = req.params.name;
let book;
try {
book = await Book.getByName("name");
} catch (err) {
console.log(err);
}
if (!book)
return res.status(404).json({ message: "No book found" });
}
return res.status(200).json({ book });
};
模型架构
这是 Skyma 模型
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bookSchema = new Schema({
name: {
type: String,
require: true
},
description: {
type: String,
require: true
},
price: {
type: Number,
require: true
},
avilable: {
type: Boolean,
},
image: {
type: String,
require: true
},
});
module.exports = mongoose.model("Book", bookSchema);
最佳答案
mongoose getByName
中没有内置方法。您可以使用通用 find使用名称
搜索对象
let book = await Book.find({ name: name }).exec();
您还可以使用findOne如果需要的话。
关于javascript - 函数编写者如何调用 getByName 。功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71942973/