我有包含“类别”的“运动”。我想创建多个具有相同类别的动作(也具有相同数据)
我只能在类别中存储一个“运动”,但是当我尝试添加另一个具有相同类别的“运动”时,我收到了著名的E11000重复键错误。
说实话,我是mongoDB的新手,我找不到任何解决方案。
这是我的代码:
类别模型:
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CategorySchema = new Schema({
name: {
type: String,
lowercase: true,
required: true
},
description: {
type: String
},
image: {
type: String
},
author: {
type: String,
required: true
}
});
module.exports = mongoose.model('Category', CategorySchema);
运动模型:
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CategorySchema = require('../models/category');
const MovementSchema = Schema({
author: {
type: String,
required: true
},
amount: { type: Number, default: 0 },
description: String,
category: CategorySchema.schema,
type: Date,
hasFinished: Boolean
});
module.exports = mongoose.model('Movement', MovementSchema);
我要存储它们的方法是通过通过ID查找一个类别,然后将该结果分配给运动。
移动保存:
function saveMovement(req, res) {
Category.findById(req.body.category, (err, cat) => {
if (err) {
res.status(500).send({ message: `Error saving the movement: ${err}` });
} else {
let movement = new Movement({
author: req.body.userid,
amount: req.body.amount,
description: req.body.description,
category: cat,
date: req.body.date
});
movement.save((err, movement) => {
if (err) {
res
.status(500)
.send({ message: `Error saving in the database: ${err} ` });
} else {
res.status(200).send({ movement });
}
});
}
});
}
如果您注意到了,我正在API中使用它,希望从正文中获得类别ID。
谢谢大家!