在Mongoose/JS中将对象推到另一个数组中的数组

f3temu5u  于 2023-05-18  发布在  Go
关注(0)|答案(1)|浏览(165)

我正在尝试将一个对象推送到Mongoose中另一个Array中的数组中。基本上就像评论评论。下面是我的schema的结构:

const Schema = new mongoose.Schema ({
  name: {type: String, required: true},
  description: {type: String, required: true},
  topics: [{name: String, description: String, responses: [{name: String, description: String}]
});

这就是我到目前为止所尝试的:

Model.findOneAndUpdate({$and: [{_id: req.body.classId}, {topics: {$elemMatch: {_id: req.body.id}}}]}, 
{$push: {responses: {name: req.body.name, description: req.body.description}}}, 
function(err, result){
  res.send(result);
});

这不会产生任何错误,并且result不是空的。我也试着在没有$and的情况下这样做:{_id: req.body.classId, 'topics._id': req.body.id'}也不行。你还能再深入一层吗?

dwthyt8l

dwthyt8l1#

您应该使用位置$运算符来:
标识数组中要更新的元素,而不显式指定该元素在数组中的位置。
例如:

import mongoose from "mongoose";
import { config } from '../../src/config';
import util from 'util';

const schema = new mongoose.Schema({
  name: String,
  topics: [{ name: String, responses: [{ name: String }] }]
});

const Model = mongoose.model('model', schema);

(async function main() {
  try {
    await mongoose.connect(config.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false });
    const docs = await Model.create([
      { name: 'name a', topics: [{ name: 'topic a', responses: [{ name: 'response a' }] }, { name: 'topic b', responses: [] }] },
      { name: 'name b', topics: [{ name: 'topic b', responses: [{ name: 'response x' }] }] }
    ]);

    const targetDocId = docs[0]._id;
    const targetTopicId = docs[0].topics[0]._id;

    const updatedDoc = await Model.findOneAndUpdate(
      {
        _id: targetDocId,
        'topics._id': targetTopicId
      },
      {
        $push: { 'topics.$.responses': { name: 'response b' } }
      },
      { new: true }
    )

    console.log('updatedDoc: ', util.inspect(updatedDoc, false, null))

  } catch (error) {
    console.error(error);
  } finally {
    // await mongoose.connection.dropCollection('models');
    await mongoose.connection.close()
  }
})();

我们将一个新的{ name: 'response b' }对象推送到topic aresponses数组中。
执行日志:

updatedDoc:  {
  _id: 6464d547fa5ad0bf39f2e93f,
  name: 'name a',
  topics: [
    {
      _id: 6464d547fa5ad0bf39f2e940,
      name: 'topic a',
      responses: [
        { _id: 6464d547fa5ad0bf39f2e941, name: 'response a' },
        { _id: 6464d547fa5ad0bf39f2e948, name: 'response b' }
      ]
    },
    { _id: 6464d547fa5ad0bf39f2e942, name: 'topic b', responses: [] }
  ],
  __v: 0
}

相关问题