Mongoose:通过POST JSON更新项目
我有编辑一些模型的pipe理页面。 当我得到模型,我把它转换成JSON,并得到这样的事情:
{ "__v": 0, "_id": "52d919c7ec31cffc17477767", "description": "Hello, teached", "points": 1300, }
这是我的玉模板
form(role='form', method='post', action='/admin/item') .form-group textarea.form-control#result(rows='20', name='result') !{JSON.stringify(item, null, '\t')} input.btn.btn-primary(type='submit', value='Send')
这是我的路由器代码
app.post('/admin/item', function (req, res) { result = JSON.parse(req.body.result); Item.update({_id: result._id}, result, function (err, result) { if (err) { res.send('error'); } else { res.send(result, 200); } }); });
而且我总是得到一个错误,但是当我手动更新每个字段时,像这样:
result = JSON.parse(req.body.result); Item.update({_id: result._id}, {description: result.description, ...
它神奇地更新。 我做错了什么?
您需要从result
对象中删除_id
字段,否则Mongoose会假设您正试图从string而不是ObjectID
_id
字段。 你也将要这样做,因为我假设每次更新文档时更新_id
可能不是你想要的行为。
编辑:
另外,如果您正在使用bodyParser
中间件,则无需bodyParser
parsingJSON。 req.body
应该从POST请求的主体中返回一个已parsing的对象字面值。 有了这个说法,改变你的路由器看起来像这样工作:
app.post('/admin/item', function (req, res, next) { var id = req.body.result._id; delete req.body.result._id; Item.update({_id: id}, req.body.result, function (err, numAffected) { // Do something after update here }); });
- 在node.js中使用express.loggerlogging错误
- 在Angular2中保护API密钥
- MongoDB-Express :: ENOTDIR:不是目录,… gssapi.js / package.json
- firebase.auth()。createUserWithEmailAndPassword Undefined不是一个函数
- 如何在应用程序path中使用socket.io
- 低优先级Express.js app.get('/ route');
- 在Express中仅为某些路由运行中间件的模式
- 用户没有定义:Nodejs / Express + Passport
- 如何在node.js中的res.send内承诺?