如何将"userid"
(它是一个字符串)添加到MongoDB中的嵌套数组"people_attending"
中?问题是我无法添加到数组people_attending
中。
下面是我的MongoDB模式:
const OrganizationSchema = new Schema({
name: {
type: String,
required: true,
unique: true,
},
register_date: {
type: Date,
default: Date.now,
},
teams: [
{
sport: {
type: String,
required: false,
},
events: [
{
date_time: {
type: Date,
offset: true,
},
opponent: {
type: String,
required: true,
},
people_attending: [String],
amenities: [String],
},
],
},
],
});
下面是我的尝试:
- 我希望找到等于给定
eventid
的事件,并将userid
添加到people_attending
数组中。
router.put("/event/attend/:orgid/:teamid/:eventid/:userid", (req, res) => {
const userid = req.params.userid;
const eventid = req.params.eventid;
const teamid = req.params.teamid;
const orgid = req.params.orgid;
console.log(teamid, userid, eventid);
Organization.findOneAndUpdate(
{ _id: orgid, "teams._id": teamid, "teams.events._id": eventid },
{
$addToSet: {
"teams.$.events.$.people_attending": userid,
},
}
)
.then((team) => {
res.status(200).json(team);
})
.catch((err) => {
res.status(400).json(err);
});
});
1条答案
按热度按时间pb3s4cty1#
找到了解决办法: