【问题标题】:Express and Mongoose-property is not being savedExpress 和 Mongoose 属性未保存
【发布时间】:2018-08-15 08:48:00
【问题描述】:

TL;DR:我正在尝试保存一个新对象,其中一个字段未保存,其他字段保存正常。

我有一个 Mongoose 架构,其中包含一个名为 superPlotId 的属性:

const mongoose = require('mongoose');
const GeoJSON = require('mongoose-geojson-schema');
const Schema = mongoose.Schema;
const plotSchema = new Schema(
    {
        ...fields...
        superPlotId: String,
        ...more fields
    },
    { strict: false },
    { bufferCommands: false }
);

//create model class
const ModelClass = mongoose.model('plot', plotSchema);

//export model
module.exports = ModelClass;

我正在尝试使用 Express 保存一个适合此架构的新对象,如下所示:

exports.newPlot = async (req, res, next) => {
    const {
        ...a bunch of fields...
        superPlotId
    } = req.body.props;
    const plot = new Plot({
        ...a bunch of fields...
        superPlotId
    });
    console.log(('new plot:', JSON.stringify(plot)));
    try {
        const newPlot = await plot.save();
        res.json(newPlot);
    } catch (e) {
        console.log("couldn't save new plot", JSON.stringify(e));
        return res.status(422).send({ error: { message: e, resend: true } });
    }
};

我知道一个格式正确的对象正在到达端点,因为上面的 console.log 显示了它:

{...bunch of fields..."superPlotId":"5a9e9f9f0f8a8026005fe1e7"}

但情节出现在我的数据库中,但没有 superPlotId 字段。

有人知道我在这里缺少什么吗?

【问题讨论】:

    标签: javascript mongodb express mongoose mongoose-schema


    【解决方案1】:

    试试这个

    try {
        let plot = new Plot();
        plot = Object.assign(plot, req.body.props);
        const newPlot = await plot.save();
        res.json(newPlot);
    } catch (e) {
        console.log("couldn't save new plot", JSON.stringify(e));
        return res.status(422).send({
            error: {
                message: e,
                resend: true
            }
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-09
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      • 1970-01-01
      • 1970-01-01
      • 2017-06-04
      • 1970-01-01
      相关资源
      最近更新 更多