【发布时间】:2020-02-13 19:04:11
【问题描述】:
我是 Node 和 Mongoose 的新手,我正在尝试使用 MERN 堆栈构建应用程序。
当我使用 mongoose 将我的数据从我的状态保存到 mongodb 时,我尝试保存的数组的内容实际上并没有得到保存。
那里的数组似乎是空的。
对应的模型如下:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const LanesSchema = new Schema(
{
lanes: [
{
id: String,
title: String,
tasks: [
{
id: String,
title: String,
status: String,
description: String,
priority: String
}
]
}
]
},
{ minimize: false }
);
const Lane = mongoose.model("Lanes", LanesSchema);
module.exports = Lane;
我认为这里的模型可能有问题,但我不确定。
我也在这里尝试过这个版本,但也没有用:
const LanesSchema = new Schema([
{
id: String,
title: String,
tasks: [
{
id: String,
title: String,
status: String,
description: String,
priority: String
}
]
}
]);
我的代码的保存部分基本上是这样的:
const express = require("express");
const router = express.Router();
const Lane = require("../models/lanes");
router.post("/save", (req, res) => {
const data = req.body;
const newLane = new Lane(data);
newLane.save(error => {
if (error) {
res.status(500).json({ msg: "Internal server error" });
return;
}
res.json({
msg: "We received your data!"
});
});
});
module.exports = router;
这是格式为 JSON 的 req.body:
[
{
"id":"1",
"title":"Open",
"tasks":[
{
"id":"1",
"title":"Test task",
"status":"Open",
"description":"Test description",
"priority":"High"
},
{
"id":"4",
"title":"Test task 4",
"status":"Open",
"description":"Test description",
"priority":"Normal"
}
]
},
{
"id":"2",
"title":"In Progress",
"tasks":[
{
"id":"2",
"title":"Test task 2",
"status":"In Progress",
"description":"Test description",
"priority":"Normal"
},
{
"id":"3",
"title":"Test task 3",
"status":"In Progress",
"description":"Test description",
"priority":"Normal"
}
]
},
{
"id":"b0d547b1-f669-418e-8558-4739b15e1ef6",
"title":"testLane",
"tasks":[
]
}
]
现在我不确定问题是什么。到目前为止,我还没有找到类似的问题。
如果我遗漏了可能导致问题的部分代码,请告诉我。
提前致谢。
【问题讨论】:
-
您可以将您的 req.body 作为 json 添加到问题中吗?
-
@SuleymanSah 我添加了 req.body。必须是 JSON 吗?
-
最好是json格式的,这样我们可以和schema对比一下。
-
@SuleymanSah 好的,我明白了。我再次更新了我的帖子。感谢您的帮助。
-
您正在尝试添加多个条目但正在使用保存,请尝试使用 insertMany。
标签: node.js reactjs mongodb mongoose mongoose-schema