ES2015 整合

原文:Documents in ES6 翻译:小虾米(QQ:509129) 进度:未完成

文档在 ES6

Asynchronous document functions return promises, and so are compatible with the ES6 yield keyword and libraries like co.

Note that the yield keyword is currently only supported in NodeJS 0.11.x with the --harmony flag.

validate()结合CO和产量的关键词

co(function*() {
      var schema = null;
      var called = false;
      var shouldSucceed = true;
      var error;

      var validate = {
        validator: function() {
          called = true;
          return shouldSucceed;
        },
        message: 'BAM'
      };

      schema = new Schema({
        eggs: {type: String, required: true, validate: validate},
        bacon: {type: Boolean, required: true}
      });

      var M = db.model('validateSchema', schema, getCollectionName());
      var m = new M({eggs: 'Sunny side up', bacon: false});

      try {
        yield m.validate();
      } catch (e) {
        error = e;
      }

      assert.ok(!error);
      assert.equal(called, true);
      called = false;

      // The validator function above should now fail
      shouldSucceed = false;
      try {
        yield m.validate();
      } catch (e) {
        error = e;
      }

      assert.ok(error);
      assert.ok(error instanceof ValidationError);

      done();
    })();

save() integrates with co and the yield keyword

populate() requires execPopulate() to work with the yield keyword

update() works with co and yield

Queries in ES6

Mongoose queries' .exec() function returns a promise, and so its compatible with the ES6 yield keyword and libraries like co.

Note that the yield keyword is currently only supported in NodeJS 0.11.x with the --harmony flag.

exec() integrates with co and the yield keyword

can call populate() with exec()

Models in ES6

Asynchronous functions on Model return promises, and so are compatible with the ES6 yield keyword and libraries like co.

Note that the functions find(), findOne(), findById(), count(), findOneAndUpdate(), remove(), distinct(), findByIdAndUpdate(), findOneAndRemove(), update(), and findByIdAndRemove() return Query objects, and so you need to use .exec() to use these functions with yield as described above.

create() integrates with co and the yield keyword

aggregate() integrates with co and the yield keyword

mapReduce() can also be used with co and yield

Last updated

Was this helpful?