gpt4 book ai didi

node.js - 更新 _id = :id with Mongoose 处的记录

转载 作者:搜寻专家 更新时间:2023-10-31 22:36:47 27 4
gpt4 key购买 nike

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

这是我的代码片段:

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 行。我没有找到正确的语法。

最佳答案

根据 this questionthis other one , Mod on _id is not allowed 当一个人试图根据它的 id 更新一个对象而不先删除它时发生。

我也找到了这个github issue它试图解释一个解决方案。它明确指出:

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.

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

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,根据文档:

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

关于node.js - 更新 _id = :id with Mongoose 处的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17250496/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com