在mongodb中推送嵌套的三级数组

时间:2019-07-10 09:31:29

标签: arrays mongodb nested

我正在制作一个应用,并使用express mongodb。我的情况是,我们有quotes数组,其中有comments数组,内部有replies数组。我想在课程过滤器之后将对象推入replies数组中。但是它没有保存在数据库中。

这是我的模特

const mongoose = require('mongoose');
const { Schema } = mongoose;

const Replies = new Schema({
  _id: Schema.Types.ObjectId,
  text: String,
});

const Comments = new Schema({
  _id: Schema.Types.ObjectId,
  text: {
    type: String,
    default: null,
  },
  by: String,
  replies: [Replies],
});

const jobSchema = new Schema(
  {
    _id: Schema.Types.ObjectId,
    quotes: [
      {
        _id: false,
        dateAdded: Number,
        price: Number,
        discountedPrice: Number,
        quotedBy: Schema.Types.ObjectId,
        comments: [Comments],
      },
    ],

  },
  { collection: 'job' },
);

mongoose.model('Job', jobSchema);

这是我正在运行的查询。

const saveReplyByUser = (jobId, tsId, commentId, reply) => {
  return Job.findOneAndUpdate(
    {
      _id: jobId,
      'quotes.quotedBy': tsId,
      quotes: {
        $elemMatch: {
          'comments._id': commentId,
        },
      },
    },
    {
      $push: {
        'quotes.comments.$.replies': {
          text: reply,
          _id: new mongoose.Types.ObjectId(),
        },
      },
    },
  )
    .then(job => {
      return job;
    })
    .catch(err => {
      console.log(err);
      return err;
    });
};

我一直处于这种状态,我可以将记录推入第二级的comments数组中,但是我无法在第三级数组中推入记录。

0 个答案:

没有答案