【问题标题】:Schema with relationship is not saved in db具有关系的架构未保存在数据库中
【发布时间】:2020-03-24 04:17:19
【问题描述】:

我正在使用基本操作 crud 创建一个 api,我正在使用 mongodb,并且我有一个模式需要来自另一个模式的信息,我以这种方式建立了关系,在第一个 shema 中我有这个。

const mongoose = require('mongoose');
const { Schema } = mongoose;

const geographicalAreaSchema = new Schema({
    name: {type: String, required: true}
})

module.exports = mongoose.model('GeographicalArea', geographicalAreaSchema);

带有引用的第二个模式

const mongoose = require('mongoose');
const { Schema } = mongoose;

const zooSchema = new Schema({
    name: { type: String, required: true },
    nit: { type: String, required: true },
    geographicalArea: { type: Schema.ObjectId, ref: "GeographicalArea" }
})

module.exports = mongoose.model('Zoo', zooSchema);

在控制器中有这个代码来保存新的动物园

const zoo = require('../models/zoo');
const mongoose = require('mongoose');
const GeographicalArea = mongoose.model('GeographicalArea');
const zooController = {};

zooController.createZoo = async(req, res) => {
    const saveZoo = new zoo({
        name: req.body.name,
        nit: req.body.nit,
        geographicalAreaName: req.body.geographicalArea.name //this item have data
    });
    await saveZoo.save()
    res.json({
        'status': 'Zoo Save'
    })
};

module.exports = zooController;

这是路由器文件

const express = require('express');
const router = express.Router();

const zoo = require('../controllers/zoo.controller');

router.post('/', zoo.createZoo)

module.exports = router;

这是索引文件

const express = require('express');
const morgan = require('morgan');
const app = express();

const { mongoose } = require('./database');

//Settings
app.set('port', process.env.PORT || 3000);

//Middlewares
app.use(morgan('dev'));
app.use(express.json());

//Routes
app.use('/api/geographicalArea', require('./routes/geographicalArea.routes'));
app.use('/api/zoo', require('./routes/zoo.routes'));

//Starting server
app.listen(app.get('port'), () => {
    console.log('Server on port', app.get('port'))
})

当我像这样向邮递员发出发帖请求时

我看看req有没有带数据

并且我调试验证数据是否保存正确,geographicArea的字段返回undefined

我不知道为什么这个属性未定义

【问题讨论】:

  • 我认为问题在于您引用了名称,但您需要使用 _id.try req.body.geographicalArea._id。
  • 另外你在对象中的键也是错误的。尝试地理区域名称的地理区域实例
  • geographicalArea字段中使用Schema.ObjectId代替Schema.ObjectId,使用Schema.Types.ObjectId
  • @RajPurohit 如果我更改地理区域名称的地理区域,应用程序崩溃,返回此错误ValidationError: Zoo validation failed: geographicalArea: Cast to ObjectID failed for value "Asia" at path "geographicalArea"
  • @metalHeadDev 感谢您的回答,但我有同样的问题,数据到达但无法存储在常量中

标签: node.js mongodb express crud database-schema


【解决方案1】:

试试这个方法。

const zoo = require('../models/zoo')
const mongoose = require('mongoose')
const GeographicalArea = mongoose.model('GeographicalArea')
const zooController = {}

zooController.createZoo: async (req, res) => {
    try {
      const zooInfo = {
        name: req.body.name,
        nit: req.body.nit,
        geographicalAreaName: req.body.geographicalArea.name
      }
      const zooSave = await zoo.create(zooInfo)
      console.log(zooInfo)
      zooSave.save()
      res.json({ status: "zoo saved "})
     } catch(error) {
       res.json({ error })
    }
  }

【讨论】:

  • 在这种情况下,const zooInfo 的数据为req.body.geographicalArea.name,但当它到达const zooSave = await zoo.create (zooInfo) zooSave 行时,会继续返回geographicalArea: undefined。在这一点上,我认为问题出在架构中
  • 我已经编辑了答案。上面console.log(zooInfo)的值是多少?
  • 这是{ name: 'Test22', nit: 'nitTest', geographicalAreaName: 'Asia' } 的值,但zoo.create(zooInfo) 是属性geographicalArea:undefined
  • 属性 geographicalArea 仍然返回 undefined
【解决方案2】:

通过仅从邮递员发送我想与动物园相关的地理区域 ID 来解决问题,这样我就可以得到包含所有信息的对象。

发送数据

    zooController.createZoo = async(req, res) => {
    const saveZoo = new zoo({
        name: req.body.name,
        nit: req.body.nit,
        geographicalArea: req.body.geographicalArea
    });
    await saveZoo.save()
    res.json({
        'status': 'Zoo Save'
    })
};

我确认我得到了数据

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多