23

MongoDBでインスタンス化されたモデル(「Place」-他のルートから機能することはわかっています)を更新しようとしていますが、適切に更新するためにしばらく時間を費やしました。また、更新されたプロパティを表示するために、「場所」を表示するページにリダイレクトしようとしています。

ノードv0.4.0、エクスプレスv1.0.7、マングース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)
});

});

私はさまざまな方法を試しましたが、うまくいかないようです。
また、3つの{name、capital、およびcontinent}変数を宣言して、それ以降の操作をブロックする方法ではありませんか?ありがとう。一般的なデバッグのヘルプもありがたいです。Console.log(name)(宣言のすぐ下)は何もログに記録しません。

翡翠の形:

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")
4

5 に答える 5

41

何かを更新する前に、ドキュメントを見つける必要があります。

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が提供する他のfindメソッドを使用できます。更新する前に、必ずドキュメントをフェッチしてください。

于 2011-02-17T06:39:22.990 に答える
25

今、私はあなたがこれを行うことができると思います:

Place.findOneAndUpdate({name:req.params.name}, req.body, function (err, place) {
  res.send(place);
});

あなたもIDで見つけることができます:

Place.findOneAndUpdate({_id:req.params.id}, req.body, function (err, place) {
  res.send(place);
});
于 2014-02-05T06:39:07.797 に答える
5

これで、idで直接検索して更新できるようになりました。これは、Mongoosev4用です。

Place.findByIdAndUpdate(req.params.id, req.body, function (err, place) {
  res.send(place);
});

言うまでもなく、更新されたオブジェクトが必要な場合は、次{new: true}のように渡す必要があります

Place.findByIdAndUpdate(req.params.id, req.body, {new: true}, function (err, place) {
  res.send(place);
});
于 2017-06-15T16:30:40.067 に答える
0

あなたの問題は、ノード0.4.0を使用していることだと思います-動作するはずの0.2.6に移動してみてください。bodyDecoderがノード>=0.3.0のreq.body.variableフィールドにデータを入力しない状態でgithubにログオンした問題があります。

于 2011-02-17T12:47:28.453 に答える
0

下の図に基づいて同様のことを行うことができます

更新しました:

私のソリューションでは、(interacting with MongoDB method like updating/creating data to the database)MongoDBをデータベースとして使用して、Nodejs MVCフレームワークで同様のシナリオを表現するためのモデル、コントローラー、およびルートを作成しました。

// user.js - this is the user model

const mongoose = require('mongoose')
const validator = require('validator')

const User = mongoose.model('User', {
  name: {
    type:  String,
    required:  true,
    trim:  true
  },
  email: {
    type:  String,
    required:  true,
    trim:  true,
    lowercase:  true,
    validate(value) {
      if (!validator.isEmail(value)) {
        throw  new  Error('Email is invalid')
      }
    }
  },
  password: {
    type:  String, 
    required:  true, 
    minlength:  7, 
    trim:  true,
    validate(value) {
      if (value.toLowerCase().includes('password')) { 
        throw  new  Error('Password cannot contain "password"') 
      } 
    } 
  },
  age: { 
    type:  Number, 
    default:  0, 
    validate(value) { 
      if (value  <  0) { 
        throw  new  Error('Age must be a positive number') 
      }
    }
  }
});   

module.exports  =  User

// userController.js**

exports.updateUser = async(req, res) => {
  const updates = Object.keys(req.body)
  const allowedUpdates = ['name', 'email', 'password', 'age']
  const isValidOperation = updates.every((update) => { 
    allowedUpdates.includes(update))
    if (!isValidOperation) {
      return res.status(400).send('Invalid updates!')
    }
    try {
      const user = await UserModel.findByIdAndUpdate(req.params.id, 
        req.body, { new: true, runValidators: true })
      if (!user) {
        return res.status(404).send({ message: 'You do not seem to be registered' })
      }
      res.status(201).send(user)
    } catch (error) {
      res.status(400).send(error)
    }
}

// **router.js**
router.patch('/user/:id', userController.updateUser)

これが誰にでも役立つことを願っています。続きを読むこともできます。

于 2019-11-25T18:43:22.540 に答える