mongodb - 在 Mongoose Schema 上推送子子文档
问题描述
考虑这 3 个架构和层次结构:一个项目有多个阶段,一个阶段有多个事件。为了将新阶段推入项目,我这样做:
Project.findOneAndUpdate(
{ slug: projectSlug },
{ $push: { stages: myNewStage } },
).then((post) => res.status(201).json({
message: 'stage created successfully',
data: post,
})).catch((error) => {
return res.status(500).json({
code: 'SERVER_ERROR',
description: 'something went wrong, Please try again',
});
});
但是,我怎样才能将新事件推送到舞台中?据我所知,子文档与文档的属性不同(例如 find、findAndUpdate)。
我的实际模式:
项目架构
const mongoose = require('mongoose');
const Stage = require('./Stages').model('Stages').schema;
const projectSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
description: {
type: String,
},
slug: {
type: String,
trim: true,
required: true,
lowercase: true,
unique: true,
},
clientSlug: {
type: String,
trim: true,
required: true,
lowercase: true,
},
stages: [Stage],
startDate: {
type: Date,
trim: true,
required: true,
},
endDate: {
type: Date,
trim: true,
required: false,
},
},
{
timestamps: true,
});
module.exports = mongoose.model('Projects', projectSchema);
阶段架构
const mongoose = require('mongoose');
const Event = require('./Events').model('Events').schema;
const stageSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
description: {
type: String,
},
slug: {
type: String,
trim: true,
required: true,
lowercase: true,
unique: true,
},
clientSlug: {
type: String,
trim: true,
required: true,
lowercase: true,
},
projectSlug: {
type: String,
trim: true,
required: true,
lowercase: true,
},
events: [Event],
},
{
timestamps: true,
});
module.exports = mongoose.model('Stages', stageSchema);
事件模式
const mongoose = require('mongoose');
const Comment = require('./Comments').model('Comments').schema;
const eventSchema = new mongoose.Schema({
_id: {
type: String,
trim: true,
lowercase: true,
},
userEmail: {
type: String,
trim: true,
required: true,
lowercase: true,
},
text: {
type: String,
},
imgUrl: {
type: String,
},
documentUrl: {
type: String,
},
stageSlug: {
type: String,
trim: true,
required: true,
lowercase: true,
},
clientSlug: {
type: String,
trim: true,
required: true,
lowercase: true,
},
projectSlug: {
type: String,
trim: true,
required: true,
lowercase: true,
},
comments: [Comment],
},
{
timestamps: true,
});
module.exports = mongoose.model('Events', eventSchema);
解决方案
鉴于您有projectSlug
and ,要将新事件推送到您的阶段数组中stageSlug
,您可以执行以下操作:
Project.findOneAndUpdate(
{
$and: [
{ slug: projectSlug },
{ 'stages.slug': stageSlug },
]
},
{
$push: { 'stages.$.events': newEvent }
}
)
.then(() => {})
.catch(() => {});
推荐阅读
- sql - 按日期在 PostgreSQL JSONB 列中的对象数组中搜索
- isabelle - 构建有用的引理
- mysql - 如何将时间从 hh:mm:ss.mmm 转换为秒和毫秒 mysql
- jquery - 获取每个表的总和值
- angular - 如何使角度材料扩展面板仅以编程方式打开,而不是在单击面板标题时打开
- json.net - 使用 protobuf.net 从给定 .proto 文件中获取 .cs 文件的最佳方法是什么
- python-2.7 - 使用日期时间预测股票价格
- c# - RestSharp“未找到”响应
- c++ - 将 std::thread 按值推入列表
- ruby-on-rails - delete_if 返回未定义的方法“包括?” 对于零:NilClass