mongodb 如果数据对象在数组中,则Nodejs表示删除该数据对象

uurity8g  于 2022-11-22  发布在  Go
关注(0)|答案(1)|浏览(132)

我想删除数组中对象id可用的数据。但它的嵌套数组我是这样做的

const getLessonByUserid = async (req, res) => {
    const userid = req.params.userid

    try {
        const temp = [];
        const getdata = await UserLessons.find().
            populate(['quizid',
                {
                    path: 'quizid',
                    populate:
                    {
                        path: 'userid',
                        populate:
                        {
                            path: 'userid',

                        },
                    },
                }
            ]);
        let dataget = getdata;

        for (let i = 0; i < dataget.length; i++) {
            // console.log(dataget[i].quizid.length)

            for (let j = 0; j < dataget[i].quizid.length; j++) {
                console.log('debug')
                console.log(dataget[i].quizid[j])

                for (let k = 0; k < dataget[i].quizid[j].userid.length; k++) {
                    console.log(dataget[i].quizid[j].userid[k].userid);

                    if (dataget[i].quizid[j].userid[k].userid._id == req.params.id) {
                        console.log('match')
                        // dataget[i].quizid[j].userid[k].userid = [];
                        dataget[i].quizid[j].remove();
                    }
                }

            }
        }

        return res.status(200).json({
            success: true,
            message: "question found succesfully",
            data: dataget
        })

    } catch (err) {
        if (err.name === 'ValidationError') {
            console.error(Object.values(err.errors).map(val => val.message))
            return res.status(400).json({ success: false, message: Object.values(err.errors).map(val => val.message)[0] })
        }
        return res.status(400).json({ success: false, message: err.message })
    }
}

但问题是dataget[i].quizid[j].remove();,我只需要隐藏/删除从数据库中删除数据:D我只需要隐藏这个数组或删除数组。如果有任何可能性,从查询中这样做,将是伟大的。
有2个型号
一是教训

const mongoose = require('mongoose');
const lessonschema = new mongoose.Schema({
    //quiz id
    quizid: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "quiz"
        }
    ],
    text: {
        type: String,
        default: ''
    },
    image: {
        type: String,
        default: ''
    },
    audio: [
        {
            type: String,
            default: ''
        }

    ],
    video: [{
        type: String,
        default: ''
    }],

    createdOn: {
        type: Date,
        default: Date.now
    }

})

exports.UserLessons = mongoose.model('lessons', lessonschema);
exports.lessonschema = lessonschema;

另一个是测验

const mongoose = require('mongoose');

const quizschema = new mongoose.Schema({

    userid: [

        {
            userid: {
                type: mongoose.Schema.Types.ObjectId,
                ref: "users"
            },
            answer: {
                type: String

            }
        }

    ],
    question:
    {
        type: String,
        // required:true
    },
    questionType: {
        type: Number,
        default: 0
        //0: text,1:moodbase,

    },

    quizRating: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "answerrating"

    }],

    voice: {
        type: String,
        default: ""
    },


});

exports.Quiz = mongoose.model('quiz', quizschema)
exports.quizschema = quizschema

我不知道这是如何从数据库中删除的。它工作正常,但从数据库中删除不是预期的。

wvt8vs2t

wvt8vs2t1#

我想您应该在mongodb中使用ArrayFilters概念

let updatedObject = {};
 Object.assign(updatedObject, {
    'UserLessons.$[i].Quiz.$[j].quizRating.$[k].anyFieldYouWant': 
    True, // For example is boolean
  });
  this.yourModel.findOneAndUpdate(
    {
      _id: id,
    },
    updatedObject,
    {
       arrayFilters: [
        {
          'i._id': firstNestedObjectId,
        },
        {
          'j._id': secondNestedObjectId,
        },
        {
          'k._id': thirdNestedObjectId,
        },
      ],
      new: true,
    },
   );

此示例用于更新字段,对于删除,您可以使用findOneAndDelete,希望这对您有用

相关问题