用Mongoose,Express,NodeJS更新模型 [英] Update model with Mongoose, Express, NodeJS

查看:121
本文介绍了用Mongoose,Express,NodeJS更新模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更新一个实例化的模型(Place - 我知道它在其他路由中工作)在MongoDB中,并花了一段时间尝试正确地这样做。我也试图重定向到查看更新的属性的place的页面。

I'm trying to update an instantiated model ('Place' - I know it works from other routes) in a MongoDB and have spent a while trying to properly do so. I'm also trying to redirect back to the page that views the 'place' to view the updated properties.

节点v0.4.0,Express v1.0.7,Mongoose 1.10.0

Node v0.4.0, Express v1.0.7, Mongoose 1.10.0

架构:

var PlaceSchema = new Schema({
name  :String
,  capital: String
,  continent: String
});

控制器/路由:

app.put('/places/:name', function(req, res) {
var name = req.body.name;
var capital = req.body.capital;
var continent = req.body.continent;
Place.update({ name: name, capital: capital, continent: continent}, function(name) {
    res.redirect('/places/'+name)
});

});

我已经尝试了一堆不同的方式,但似乎没有得到它。

另外,不是我如何声明三个{名称,资本和大陆}变量阻止进一步的操作?谢谢。一般调试帮助也不胜感激。 Console.log(name)(在声明之下)不记录任何内容。

I've tried a bunch of different ways but can't seem to get it.
Also, isn't how I declare the three {name, capital, and continent} variables blocking further operations? Thanks. General debugging help is also appreciated. Console.log(name) (right below the declaration) doesn't log anything.

玉形式:

h1 Editing #{place.name}
form(action='/places/'+place.name, method='POST')
  input(type='hidden', name='_method', value='PUT')
  p
    label(for='place_name') Name:
    p
    input(type='text', id='place_name', name='place[name]', value=place.name)
    p
    label(for='place_capital') Capital: 
    p
    input(type='text', id='place_capital', name='place[capital]', value=place.capital)
    p
    label(for='place_continent') Continent:
    p
    textarea(type='text', id='place_continent', name='place[continent]')=place.continent
    p
    input(type="submit")


推荐答案

您必须在更新任何内容之前找到该文档:

You have to find the document before updating anything:

Place.findById(req.params.id, function(err, p) {
  if (!p)
    return next(new Error('Could not load Document'));
  else {
    // do your updates here
    p.modified = new Date();

    p.save(function(err) {
      if (err)
        console.log('error')
      else
        console.log('success')
    });
  }
});

在生产代码中使用您拥有的相同设置。而不是findById,您可以使用mongoose提供的任何其他查找方法。只需确保在更新文档之前获取文档。

works for me in production code using the same setup you have. Instead of findById you can use any other find method provided by mongoose. Just make sure you fetch the document before updating it.

这篇关于用Mongoose,Express,NodeJS更新模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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