用猫鼬更新_id =:id的记录 [英] Update a record where _id = :id with Mongoose

查看:88
本文介绍了用猫鼬更新_id =:id的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Mongoose更新现有记录.插入可以,但不能更新.

I'm trying to update an existing record with Mongoose. The insert is OK but not the update.

这是我的摘录:

app.post('/submit', function(req, res) {

    var my_visit = new models.visits({
        date: req.body.visit_date,
        type: req.body.visit_type,
        agency: req.body.visit_agency,
        city: req.body.visit_city,
        url: req.body.visit_url,
        note: req.body.visit_note
    });

    // INSERT
    if(req.body.id == 0) {
        my_visit.save(function(err) {
            if(err) { throw err; }

            console.log('added visit');

            res.redirect('/');
        });
    } else { // UPDATE
        var upsertData = my_visit.toObject();

        console.log(req.body.id); // OK

        models.visits.update({ _id: req.body.id }, upsertData, { multi: false }, function(err) {
            if(err) { throw err; }

            console.log('updated visit: '+ req.body.id);

            res.redirect('/');
        });
    }


})

响应为Mod on _id is not allowed.

我只想更新MySQL中的WHERE id = id等行.我找不到正确的语法.

I just want to update the line such as WHERE id = id in MySQL. I didn't find the right syntax.

推荐答案

根据另一个问题Mod on _id is not allowed发生在一个尝试根据对象的ID更新对象,而不先删除它.

According to this question and this other one, the Mod on _id is not allowed occurs when one tries to update an object based on its id without deleting it first.

我还发现了这个 github问题,它试图解释一种解决方案.它明确指出:

I also found this github issue which tries to explain a solution. It explicitly states:

请注意不要将现有模型实例用于update子句 (这将不起作用,并且可能会导致诸如无限循环之类的怪异行为). 另外,请确保update子句不具有_id属性, 这会导致Mongo返回不允许对_id进行修改"错误.

Be careful to not use an existing model instance for the update clause (this won't work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an _id property, which causes Mongo to return a "Mod on _id not allowed" error.

看来,解决方案是执行以下操作:

The solution, it seems, is to do the following:

var upsertData = my_visit.toObject();

console.log(req.body.id); // OK

delete upsertData._id;

models.visits.update({ _id: req.body.id }, upsertData, { multi: false }, function(err) {
    if(err) { throw err; }
    //...
}


另一方面,您可能可以重写路由,以执行创建和更新操作,而无需使用if-else子句. update()需要一个额外的选项upsert,根据文档:


On a side note, you can probably rewrite your route to do both the create and update without the if-else clause. update() takes an extra option upsert, which, according to the docs:

upsert(布尔值)是否创建不匹配的文档(假)

upsert (boolean) whether to create the doc if it doesn't match (false)

这篇关于用猫鼬更新_id =:id的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆