更新和删除在嵌套文档中不起作用

时间:2019-07-13 12:09:39

标签: javascript node.js mongodb mongoose

我的两个猫鼬功能(更新和删除)不会引发任何错误,但不会更新/删除任何东西。

我尝试研究“ $”运算符,但这没有任何帮助(仍然发生相同的问题)。我发现的大多数教程都只涉及更新/删除未嵌套的内容。我对处理嵌套文档的了解很弱。

用户模型

const userSchema = new mongoose.Schema({
    username: { type: String, required: true, unique: true },
    email: { type: String, required: true, unique: true},
    password: { type: String, required: true },
    decks: [{type: mongoose.Schema.Types.ObjectId, ref: 'Deck'}]
});

const deckSchema = new mongoose.Schema({
    name: { type: String, require: true },
    cards: [{type: mongoose.Schema.Types.ObjectId, ref: 'Card'}]
});

const cardSchema = new mongoose.Schema({
    front: { type: String },
    back: { type: String },
    example: [{ type: String }]
});

const User = mongoose.model('User', userSchema);
const Card = mongoose.model('Card', cardSchema);
const Deck = mongoose.model('Deck', deckSchema);
module.exports = {User, Card, Deck}

猫鼬删除/更新

    const removeDeck = async (userId, deckId) => {
        return user = await User.findOneAndUpdate(
            { _id: userId },
            {
                $pull: { decks: { _id: deckId } }
            }
        )
    }

    const removeCard = async (userId, cardId) => {
        return rCard = await User.findOneAndUpdate(
            { _id: userId },
            {
                $pull: { decks: { cards:  {   _id: cardId } } }
            }
        )
    }


    const updateDeckName = async (userId, deckId, updatedName) => {
        const newDeck = await User.findOneAndUpdate(
            {
                _id: userId,
                decks: { $elemMatch: {_id: deckId}}
            },
            {
                $set: { 'decks.name': updatedName }
            }
        )
        return newDeck
    }

    const updateCard = async (userId, cardId, updatedText) => {
        return await User.findOneAndUpdate({ _id: userId, 'decks.cards._id': cardId },
            {
                $set: { 'cards.front': updatedText.front, 'cards.back': updatedText.back }
            }
        )
    }

没有引发错误,但是两个更新函数均返回null。

0 个答案:

没有答案