【问题标题】:Can't update values in mongodb database无法更新 mongodb 数据库中的值
【发布时间】:2022-01-26 16:03:05
【问题描述】:

运行后用户名不会更新。我也尝试过 UpdateOne,但效果不佳。该代码应该更新一个数组,但我尝试更新用户名以便更容易追踪问题。

const mongoose = require('mongoose');

const schema = mongoose.Schema;

const userSchema = new schema({
    Username:{
        type: String,
        required: true
    },
    Password:{
        type: String,
        required: true
    },
    Cart: Array
});

const User = mongoose.model('User', userSchema);
module.exports = User;

.

app.post('/putbox', (req, res) => {


    var query = { Username: user };

    var newvalues = { $push: { Cart: "Boxing" } };

    try{

        User.find(query).then((d)=>{

            var values = d[0].Cart;
            values.push("boxing")

            User.findByIdAndUpdate(d._id, {Username: "test1"})

        });

    } catch(err) {
        console.log(err);
    } 

    res.redirect('/boxing');

});

【问题讨论】:

  • 您打算将密码存储为明文吗?

标签: javascript node.js mongodb


【解决方案1】:

我认为语法不正确。 updateOne 的第一个元素搜索要更新的匹配项。您只是在传递d._id,这与您的数据库结构中的_id 键不同。试试这个

User.updateOne({ _id: d._id }, {Username: "test1"})

【讨论】:

    猜你喜欢
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 2020-12-08
    • 1970-01-01
    相关资源
    最近更新 更多