我正在尝试让Joi使用我的nodejs api,但它无法正常工作。 我做错了什么?这是我的商业模式:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Joi = require('@hapi/joi');
// Define collection and schema for Business
let Business = new Schema({
model: {
type: Joi.string().alphanum().min(2).max(255).required()
},
brand: {
type: Joi.string().alphanum().min(2).max(255).trim()
},
price: {
type: Joi.number().positive()
},
photo: {
type: Joi.string().max(255).trim()
}
},{
collection: 'business'
});
module.exports = mongoose.model('Business', Business);
这是我的业务路线:
const express = require('express');
const businessRoutes = express.Router();
// Require Business model in our routes module
let Business = require('./business.model');
// Defined store route
businessRoutes.route('/add').post(function (req, res) {
let business = new Business(req.body);
business.save()
.then(business => {
res.status(200).json({'business': 'business in added successfully'});
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
// Defined get data(index or listing) route
businessRoutes.route('/').get(function (req, res) {
Business.find(function(err, businesses){
if(err){
console.log(err);
}
else {
res.json(businesses);
}
});
});
// Defined edit route
businessRoutes.route('/edit/:id').get(function (req, res) {
let id = req.params.id;
Business.findById(id, function (err, business){
res.json(business);
});
});
// Defined update route
businessRoutes.route('/update/:id').post(function (req, res) {
Business.findById(req.params.id, function(err, business) {
if (!business)
res.status(404).send("data is not found");
else {
business.model = req.body.model;
business.brand = req.body.brand;
business.price = req.body.price;
business.photo = req.body.photo;
business.save().then(business => {
res.json('Update complete');
})
.catch(err => {
res.status(400).send("unable to update the database");
});
}
});
});
// Defined delete | remove | destroy route
businessRoutes.route('/delete/:id').get(function (req, res) {
Business.findByIdAndRemove({_id: req.params.id}, function(err, business){
if(err) res.json(err);
else res.json('Successfully removed');
});
});
module.exports = businessRoutes;
如果我尝试定义let Business = Joi.object().keys
,则会抛出错误。
我认为我应该将let Business
更改为其他名称,但我不知道,因为这是我的第二个nodejs应用程序,并且我对后端工作有点陌生。
答案 0 :(得分:0)
我能够使用joigoose
现在这是我的商业模式
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Joigoose = require('joigoose')(mongoose);
const Joi = require('@hapi/joi');
// Define collection and schema for Business
var joiSchema = Joi.object({
model: Joi.string().alphanum().min(2).max(255).trim().required(),
brand: Joi.string().alphanum().min(2).max(255).trim().required(),
price: Joi.number().positive(),
photo: Joi.string().max(255).trim()
})
var Business = new Schema(Joigoose.convert(joiSchema))
module.exports = mongoose.model('Business', Business);