【问题标题】:Mongoose update not updating document猫鼬更新不更新文档
【发布时间】:2016-05-24 18:16:57
【问题描述】:

我正在尝试通过 Mongoose 更新我的 MongoDB 中的文档,但由于某种原因无法找到请求的文档...

Call.update({_id: data.call._id}, { $set: { approved: value }}, function (error, response) {
    console.log(error);
    console.log(response);
    if (error) {
        callback(error, null);
    } else {
        callback(null, response);
    }
});

data.call._id 包含一个有效的文档_id 并且approved 的类型是Number

response 输出以下内容:

{ ok: 1, nModified: 0, n: 0, lastOp: { _bsontype: 'Timestamp', low_: 0, high_: 0 }, electionId: 56a92375bfb5c1abc4e825a7 }

数据库中的文档永远不会更新...value 将被设置为 1-1,具体取决于之前的条件。

型号:

const callSchema = new Schema({
    start: Date,
    duration: String,
    callerNumber: String,
    callerNumberAreaCode: String,
    trackingNumber: String,
    destinationNumber: String,
    answered: String,
    customerId: String,
    approved: Number
}, { collection: 'calls'});

const Call = mongoose.model('Call', callSchema);

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    希望这可以帮助某人。

    确保您的 Scheme 的 FIELD 与 $set 子句中的 FIELD 完全正确。

    例如:

    如果您的更新是(设置address 字段):

    User.update({_id: mongoose.Types.ObjectId("<doc_id>")}, { $set: { address: "New York" }}, function (err, res) {
        if (err) {
            console.log("err:", err)
        } else {
            console.log("success with response:", res)
        }
    })
    

    你的方案需要包含address字段,如:

    let User = new mongoose.Scheme({
        name: String,
        address: String
    })
    

    感谢阅读。

    【讨论】:

    • 非常感谢你。我一直在为这个做头发。
    【解决方案2】:

    Model.update 中,您不需要使用$set。试试这个:

    Call.update({_id: data.call._id}, { approved: value }, function (error, response) {
        console.log(error);
        console.log(response);
        if (error) {
            callback(error, null);
        } else {
            callback(null, response);
        }
    });
    

    【讨论】:

    • 在数据库中实际查找文档时存在问题。我刚刚用findOne() 方法替换了它,这个函数的响应是空的,即使试图找到的文档存在于数据库中。
    • findOne(_id: ObjectId(data.call._id))const ObjectId = mongoose.Types.ObjectId; 试试这个
    • null 仍在返回中
    • 嗯,我现在有点困惑。没有下划线? id: ObjectId(data.call._id)
    • 我刚刚尝试使用硬编码的 ID 运行 findOne(),但仍然为空,我已将模型添加到原始帖子中...据我所知,一切都是好吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 2021-12-31
    • 2012-03-28
    • 2012-04-29
    • 2020-10-18
    相关资源
    最近更新 更多