在猫鼬模式下推送子子文档

请考虑以下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,lowercase: true,unique: true,clientSlug: {
    type: String,stages: [Stage],startDate: {
    type: Date,endDate: {
    type: Date,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,projectSlug: {
    type: String,events: [Event],});

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,userEmail: {
    type: String,text: {
    type: String,imgUrl: {
    type: String,documentUrl: {
    type: String,stageSlug: {
    type: String,comments: [Comment],});

module.exports = mongoose.model('Events',eventSchema);
wkao0705120104 回答:在猫鼬模式下推送子子文档

要在您拥有projectSlugstageSlug的情况下将新事件推送到您的stage数组中,可以执行以下操作:

Project.findOneAndUpdate(
  {
    $and: [
      { slug: projectSlug },{ 'stages.slug': stageSlug },]
  },{
    $push: { 'stages.$.events': newEvent }
  }
)
.then(() => {})
.catch(() => {});
本文链接:https://www.f2er.com/3156588.html

大家都在问