我正在尝试使用node js(Express)和mongo DB在两个表(Group和Movement表)之间建立一种One-To-Many
关系。我已经有一个group Id
来自我方的分组表,我的问题是,如何保存带有我的group Id
的动作(请参阅第3点)。我尝试通过groupId: req.body.group._id
并
groupId: req.body.group
,但我永远无法填充该变量
这是我创建的两个实体:
1)组实体
const mongoose = require("mongoose")
const GroupSchema = mongoose.Schema({
name: {
type: String,
required: true
},
limit: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
},
movement: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Movement' }],
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
})
module.exports = mongoose.model("Group", GroupSchema)
2)运动实体
const mongoose = require("mongoose")
const MovementSchema = mongoose.Schema({
description: {
type: String,
required: true
},
value: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
},
group: { type: mongoose.Schema.Types.ObjectId, ref: 'Group' }
})
module.exports = mongoose.model("Movement", MovementSchema)
这是我做端点的移动路由器(实际问题在这里)
3)运动路线
const router = require('express').Router();
const verify = require('./verifyToken');
const User = require('../model/User');
const Group = require('../model/Group');
const Movement = require('../model/Movement');
// Create Movement
router.post('/', verify, async (req, res) => {
const post = new Movement({
description: req.body.description,
value: req.body.value,
groupId: req.body.group._id //**tried this**
});
try {
const savedMovement = await post.save()
res.status(200).send(res.json({ data: savedMovement }));
} catch (error) {
res.status(400).send(res.json({ message: error }));
}
});
module.exports = router;
请求已发送
{
"description":"group1",
"value":"233",
"group":"5e506f3c56233d08f79bc8f3"
}
答案 0 :(得分:1)
如果console.log(req.body)
为您提供了此信息:
{
description: 'group1',
value: '233',
group: '5e506f3c56233d08f79bc8f3'
}
..您应该能够做到这一点:
router.post('/', verify, async (req, res) => {
console.log(req.body) // --> { description: 'group1', value: '233', group: '5e506f3c56233d08f79bc8f3' }
const post = new Movement({
description: req.body.description,
value: req.body.value,
groupId: req.body.group
// groupId: req.body.group._id //**tried this**
});
try {
const savedMovement = await post.save()
res.status(200).send(res.json({ data: savedMovement }));
} catch (error) {
res.status(400).send(res.json({ message: error }));
}
});