Mongoose: 在保存后保留 isNew 状态

创建于 2013-05-07  ·  14评论  ·  资料来源: Automattic/mongoose

现在知道该对象是否在 post save 中间件中是新的仍然很重要,我相信它设置为 false 它应该在 post save 后设置为 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 被创建并且为真。 但是在保存后,这个标志没有定义(所以我得到一个未定义的)。

有什么我做错了吗? 这就像 _this_ 的范围在两个函数之间没有保留(或绑定)。

我试过猫鼬版本,一个是从 npm ('3.9.8-pre') 安装的,另一个是从这个 repo 构建的......有人有什么建议吗?

我知道我的 Schema 不需要包含 _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 版本中考虑它。

大家好 !

此内置功能的任何更新?

当我尝试保存新文档时,猫鼬_(5.4.19)_上不存在wasNew

@darkterra wasNew不存在,您需要在pre内创建它,然后可以在post内使用,如上述评论https://github.com/Automattic/猫鼬/问题/1474#issuecomment -17669982

@thakurinbox ,感谢您的回复。

如果我正确理解原始帖子的问题是“保留isNew _in the postSave hook_”,那么@emanuelecasadio@lbstr@vkarpov15似乎说在“postSave”中内置这些数据会很好 _ (无论是属性“isNew”还是“wasNew”)_。

我没有'isNew'或'wasNew',所以我想知道'isNew'属性是否不再存在,是否会被'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 :)')
    }
  });
})

_那里没有isNewwasNew :_

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 等级