Mongoose: 保存後のisNew状態の保持

作成日 2013年05月07日  ·  14コメント  ·  ソース: Automattic/mongoose

オブジェクトがポスト保存ミドルウェアで新しいかどうかを知ることは依然として重要です。これはfalseに設定されていると思いますが、ポスト保存後にfalseに設定する必要があります。

new feature

最も参考になるコメント

schema.pre('save', function (next) {
  this.wasNew = this.isNew;
  next();
})

schema.post('save', function () {
  if (this.wasNew) {
     // ...
  }
})

全てのコメント14件

schema.pre('save', function (next) {
  this.wasNew = this.isNew;
  next();
})

schema.post('save', function () {
  if (this.wasNew) {
     // ...
  }
})

これにより、wasNewプロパティが保持されますか?

スキーマに追加しない限り、

こんにちは、

私が持っているコードの一部でこれを使用しようとしていますが、なぜこれが機能しないのかわかりません。 保存前にwasNewが作成され、trueになります。 ただし、保存後では、このフラグは定義されていません(したがって、未定義になります)。

私が間違っていることがありますか? これは、_this_のスコープが両方の関数間で保持(またはバインド)されていない場合のようなものです。

1つはnpm( '3.9.8-pre')からインストールされ、もう1つはこのリポジトリから構築されたバージョンのマングースを試しました...誰か提案がありますか?

スキーマに_wasNew_フィールドを含める必要がないことを理解しましたが、そうですか?

前もって感謝します!

コード:

module.exports = function (schema) {

    log.info("Inside functions");

    schema.pre('save', function (next) {
        log.info('pre saving...');

        this.wasNew = this.isNew;
        var self = this;
        if (self.isNew) {
            self.information.token = require('crypto').randomBytes(48).toString('hex');
            self.profile.name = (self.email.split("@"))[0];
        }
        next();
    });

    schema.post('save', function (doc) {
        log.info('post saving...', this);

        if (this.wasNew) {
            log.info("Sending email");
            mailingService.welcome(this.email);
        }

        var bond = {
            "name": doc.profile.name,
            "owner": doc._id
        };

        log.info(bond);

        dbHelper.createBond(bond);
    });
};

こんにちは。_this.wasNew_を_doc.wasNew_に変更し、正常に動作しています。 また、フィールドは必要に応じてドキュメントに保存されません。

これは正しいですね。

ありがとう!

うん:)

皆さん、この調整は、すべてのスキーマのデフォルトとして現在のブランチに実際に追加する必要があります。

wasNewを組み込むべきではない理由は何ですか? マングースに追加する必要がありますか?

合理的なアイデアです。今後の5.xリリースで検討します。

みなさん、こんにちは!

この組み込み機能の更新はありますか?

新しいドキュメントを保存しようとすると、 wasNewがマングース_(5.4.19)_に存在しません

@darkterra wasNewはありません。 pre内に作成する必要があります。上記のコメントhttps://github.com/Automattic/で述べたように、 post内で使用できます。マングース/ issues / 1474#issuecomment -17669982

@thakurinbox 、ご回答ありがとうございます。

元の投稿の質問が「isNewを保存する_postSaveフックに_」であることが正しく理解されている場合、@ emanuelecasadio 、@ lbstr 、および@ vkarpov15は、このデータを「postSave」に組み込むとよいと言っているようです。プロパティ 'isNew'または 'wasNew')_であるかどうか。

「isNew」または「wasNew」を持っていないので、「isNew」プロパティはもう存在せず、futureによって「wasNew」に置き換えられるのではないかと思いました。

_コードの少しの平和:_

'use strict';

const mongoose = require('mongoose');  // v5.4.19

const connect = mongoose.connect('mongodb://localhost/test_mongoose', { useNewUrlParser: true });
console.log('mongoose connect: ', connect);

connect.then(connectionObject => {
  const Schema = mongoose.Schema;

  const BlogPost = new Schema({
    title: String,
    body: String,
    date: Date
  });

  BlogPost.pre('save', function(next, doc, err) {
    console.log('pre: this: ', this);
    console.log('pre: doc: ', doc);
    next();
  });

  BlogPost.post('save', function(doc, next) {
    console.log('post: this: ', this);
    console.log('post: doc: ', doc);
    next();
  });

  const BlogModel = mongoose.model('BlogPost', BlogPost);


  const newBlogPost = new BlogModel({
    title: 'This is a test',
    body: 'This is the BEST POST ever !!!!!',
    date: new Date()
  });

  console.log('newBlogPost: ', newBlogPost);

  newBlogPost.save((err, doc) => {
    if (err) {
      console.error(err);
    }
    else
    {
      console.log('callback SAVE: ', doc);
      console.log('Post SAVED :)')
    }
  });
})

_そして、そこにisNewまたはwasNewはありません:_

mongoose connect:  Promise { <pending> }

newBlogPost:  { _id: 5c90aeb34f000a254ed2b6f7,
  title: 'This is a test',
  body: 'This is the BEST POST ever !!!!!',
  date: 2019-03-19T08:56:19.011Z }

pre: this:  { _id: 5c90aeb34f000a254ed2b6f7,
  title: 'This is a test',
  body: 'This is the BEST POST ever !!!!!',
  date: 2019-03-19T08:56:19.011Z }

pre: doc:  SaveOptions {}

post: this:  { _id: 5c90aeb34f000a254ed2b6f7,
  title: 'This is a test',
  body: 'This is the BEST POST ever !!!!!',
  date: 2019-03-19T08:56:19.011Z,
  __v: 0 }

post: doc:  { _id: 5c90aeb34f000a254ed2b6f7,
  title: 'This is a test',
  body: 'This is the BEST POST ever !!!!!',
  date: 2019-03-19T08:56:19.011Z,
  __v: 0 }

callback SAVE:  { _id: 5c90aeb34f000a254ed2b6f7,
  title: 'This is a test',
  body: 'This is the BEST POST ever !!!!!',
  date: 2019-03-19T08:56:19.011Z,
  __v: 0 }

Post SAVED :)

明らかに、コンソールはこれらのメソッドだけでなくオブジェクトの他のプロパティも表示できないようですが、preSaveで「this.isNew」と「this.isModified()」を呼び出そうとすると、次のようなものがあります。コンソールに表示されます...

  BlogPost.pre('save', function(next, doc, err) {
    console.log('pre: this: ', this);
    console.log('pre: doc: ', doc);
    console.log('pre: this.isNew: ', this.isNew); // true
    console.log('pre: this.isModified(): ', this.isModified()); // true

    this.wasNew = this.isNew;

    console.log('pre: this.wasNew: ', this.wasNew); // true
    next();
  });

したがって、この問題のトリックがうまく機能することを確認します。 一方、過去には、コンソールは、Mongooseによって定義されたオブジェクトの関数やその他のプロパティを表示できると確信しています。

この機能の更新はまだありません。そのため、この問題はまだ開いています:+1:。 事前保存でwasNewを手動で設定するのが今のところ行く方法です

このページは役に立ちましたか?
0 / 5 - 0 評価