简体   繁体   中英

How to update only specific field in object within an array Mongodb

Expense Tracker application: Nodejs, Mongodb

Trying to Create a function that will update only the passed fields from request inside an array of objects

Database Schema

数据库模式

const updateExpense = async (req, res) => {
try {
    let db = mongo.getDb()
    let { macro, micro, amount, note } = req.body;
    let { username, id } = req.query
    let expense = await db.collection("Expense").updateOne({ username: username, "expenses.expense_id": ObjectId(id) }, { $set: { 
        "expenses.$.macro": macro,
        "expenses.$.micro": micro,
        "expenses.$.amount": amount,
        "expenses.$.note": note }
     });
    res.status(200).json({
        message: "Expense Updated",
        expense: expense
    });
} catch (err) {
    res.status(500).json({
        message: err.message
    });
}
}

The above function is replacing all other fields with null

If the user is passing only the micro field, then the other fields should remain the same and only the micro field should change and other fields should not change.

Need A MongoDB Query which will only change what is required based on the data passed in req

I think you must first fetch from the database with findOne then update that fields set in req.body , something like this:


const updateExpense = async (req, res) => {
try {
    let db = mongo.getDb()
    let { macro, micro, amount, note } = req.body;
    let { username, id } = req.query
    let expense = await db.collection("Expense").findOne({ username: username });
    let special_ex = expense.expenses.find(ex => ex.expense_id === ObjectId(id);
    special_ex.macro = macro ? macro : special_ex.macro;
    special_ex.micro = micro ? micro : special_ex.micro;

/*
    and so on ...
*/    

    await expense.update();

    res.status(200).json({
        message: "Expense Updated",
        expense: expense
    });
} catch (err) {
    res.status(500).json({
        message: err.message
    });
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM