Express 和 Mongoose-属性 未保存
Express and Mongoose-property is not being saved
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 字段。
有人知道我在这里遗漏了什么吗?
试试这个
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
}
});
}
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 字段。
有人知道我在这里遗漏了什么吗?
试试这个
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
}
});
}