【发布时间】:2020-07-12 04:43:02
【问题描述】:
我是开发和表达社区的新手。我正在构建一个咖啡馆评论应用程序作为一个宠物项目。我正在使用带有 mongoose 的 express 框架 mongoDB。我可以将单个对象保存到文档中,但是在保存多个对象时,我似乎无法弄清楚。我不断收到 Cafe validation failed: name: Cast to String failed for value "[ 'Cafe X', 'Cafe Y' ]" at path "name" 的验证错误。然后我尝试了 insertMany 函数,但随后我收到一条错误消息 cafe.insertMany 不是函数。我想我必须将咖啡馆作为对象数组插入,但是如何将它放入对象数组中?有人能指出我正确的方向吗?
架构在 cafe.js 文件中定义如下:
const mongoose = require('mongoose');
const cafeSchema = new mongoose.Schema({
name: {
type: String,
trim: true,
required: true
},
chef: {
type: String,
trim: true
},
city: {
type: String,
required: true,
max: 32,
trim: true
},
rating: {
type: Number,
required: true
},
contactNumber: {
type: String,
trim: true,
required: true
}
});
module.exports = mongoose.model('Cafe', cafeSchema);
路由文件如下:
var express = require('express');
var router = express.Router();
const cafeController = require('../controllers/cafeController');
/* GET home page. */
router.get('/', cafeController.addCafeGet);
router.post('/', cafeController.addCafePost);
module.exports = router;
cafeController如下,对单个对象效果很好:
const Cafe = require('../models/cafe');
exports.addCafeGet = (req, res) => {
res.render('index', { title: 'Add Restourant' });
};
exports.addCafePost = async (req, res, next) => {
try {
const cafe = new Cafe(req.body);
await cafe.save();
res.json(cafe);
} catch (error) {
next(error);
}
};
在 html 中,用户/管理员添加了咖啡馆的。稍后他们将能够同时添加更多咖啡馆,例如我只有两个。
form(action="", method="post")
ul
li
input(type="text" name='name' placeholder='name')
li
input(type="text" name='city' placeholder='City')
li
input(type="text" name='chef' placeholder='Chef')
li
select#rating(name="rating")
option(value="1") 1
option(value="2") 2
option(value="3") 3
option(value="4") 4
option(value="5") 5
li
input(type="text" name='contactNumber' placeholder='Contact number')
ul
li
input(type="text" name='name' placeholder='name')
li
input(type="text" name='city' placeholder='City')
li
input(type="text" name='chef' placeholder='Chef')
li
select#rating(name="rating")
option(value="1") 1
option(value="2") 2
option(value="3") 3
option(value="4") 4
option(value="5") 5
li
input(type="text" name='contactNumber' placeholder='Contact number')
button(type="submit") SAVE
我也计划在稍后阶段使用前端框架,但不是现在。
【问题讨论】:
标签: javascript arrays node.js express mongoose