【问题标题】:Generating an array of objects for insertMany in mongoose with express and node使用express和node在mongoose中为insertMany生成一个对象数组
【发布时间】: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


    【解决方案1】:

    您尝试实现的目标可能存在其他问题,但请查看res.json(restourant)restourant 指的是什么?

    这样的事情在这种情况下可能会起作用:

    // cafeController
    exports.addRestourantPost = async (req, res, next) => {
      try {
        const cafe = new Cafe(req.body);
        const savedCafe = await cafe.save();
        res.status(201).json(savedCafe.toJSON());
      } catch (error) {
        next(error);
      }
    };
    

    【讨论】:

    • 感谢您的信息。提到餐厅实际上应该是咖啡馆。我在发布问题时犯了一个错误。更改咖啡馆控制器无助于解决无法将两个对象推送到数据库的问题。错误:Cafe 验证失败:名称:Cast to String 值“['Cafe X','Cafe Y']”在路径“name”处失败,城市:Cast to String 值“['City X”失败', 'City Y' ]" at path "city" 等。将对象转换为正确格式可能是个问题,但我不确定。我需要能够同时将多个对象推送到数据库。
    • 好的,我确信有很多方法可以解决这个问题,但我可能会从 HTML 开始。也许它可以通过打开下一个表单的“添加咖啡馆”按钮动态创建。这样,您可以将函数链接到创建 cafe 对象并将其添加到数组的按钮。然后,当点击“提交”按钮时,另一个函数会循环遍历这个咖啡馆数组并分别发布它们。
    猜你喜欢
    • 2021-12-20
    • 2012-08-26
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    相关资源
    最近更新 更多