我有一个mongodb文档“ team”,我想通过Nodejs-mongoose应用程序将Teammate推送到一个数组。
队友是具有一些附加属性的人员参考。 假设额外的属性仅在Team文档中相关,因此我不想将其存储在person文档中。
问题是:推送未将所有预期的属性添加到团队文档中的队友数组。
预期的行为:人员对象引用,人员名称,人员roleInTeam和注释数据将添加到“团队”文档中的“队友”数组中。
相反,在更新/推送之后,Teammates数组仅包含人员参考及其名称。
我猜问题出在$ push语句周围,但是找不到正确的语句。 请帮忙 :) 谢谢!
更新/推送后的结果小组文档:
{
"_id": {
"$oid": "5b596eefa8b2793a642938be"
},
"teamTitle": "Team1",
"teammates": [
{
"_id": {
"$oid": "5b596f13a8b2793a642938bf"
},
"name": "Leader John"
},
{
"_id": {
"$oid": "5b5970eba66ced0e580444fb"
},
"name": "Tester John "
}
],
"date": {
"$date": "2018-07-26T06:49:19.683Z"
},
"__v": 0
}
预期结果将是这样:
...
"teammates": [
{
"_id": {
"$oid": "5b596f13a8b2793a642938bf"
},
"name": "Leader John",
"roleInTeam": "Leader",
"comment": "Blackbelt tech lead"
},
...
现在这是我的代码(我跳过了app.js,在这里不重要)
这是团队模式:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const TeamSchema = new Schema({
teamTitle: {
type: String,
required: true
},
teammates: [
{
teammate: {
type: Schema.Types.ObjectId,
ref: 'persons'
},
name: {
type: String,
required: true
},
roleInTeam: {
type: String,
required: true
},
comments: {
type: String
}
}
],
date: {
type: Date,
default: Date.now
}
});
module.exports = Team = mongoose.model('team', TeamSchema);
以下是在团队中引用的Person模式:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const PersonSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = Person = mongoose.model('persons', PersonSchema);
这是可以执行推送的api代码:
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Team = require('../../models/Team');
const Person = require('../../models/Person');
// @route POST api/team/teammate
// @desc Add one teammate to the team if not exists
router.post(
'/teammate',
(req, res) => {
const errors = {};
//new teammate data
const newTeammate = Person({
_id: mongoose.Types.ObjectId(),
name: req.body.name,
email: req.body.email
});
Team.findOne({ "teammates.name": newTeammate.name}).then(team =>
{
if (team) {
errors.name = 'There is a teammate with identical name';
res.status(400).json(errors);
} else
{
newTeammate.save().then(newTeammate => {
if (newTeammate) {
Team.findOneAndUpdate(
{ _id: req.body.id },
{ $push: { teammates: newTeammate, name: newTeammate.name, roleInTeam: req.body.roleInTeam, comment: req.body.comment } },
{ new: true }
).then(team => res.json(team));
}
}).then(console.log('Teammate added'));
}
});
}
);
module.exports = router;