MongoDB
 sql >> Teknologi Basis Data >  >> NoSQL >> MongoDB

Di Mongoose Model.find() dan Model.find().exec() menghasilkan hasil yang sama. Jadi mengapa repot-repot menggunakan Model.find().exec()?

Luwak telah menjelaskan perbedaan keduanya di janji ,

Dengan contoh:

const doc = await Band.find({ name: "Guns N' Roses" }); // works

const badId = 'this is not a valid id';
try {
  await Band.find({ _id: badId });
} catch (err) {
  // Without `exec()`, the stack trace does **not** include the
  // calling code. Below is the stack trace:
  //
  // CastError: Cast to ObjectId failed for value "this is not a valid id" at path "_id" for model "band-promises"
  //   at new CastError (/app/node_modules/mongoose/lib/error/cast.js:29:11)
  //   at model.Query.exec (/app/node_modules/mongoose/lib/query.js:4331:21)
  //   at model.Query.Query.then (/app/node_modules/mongoose/lib/query.js:4423:15)
  //   at process._tickCallback (internal/process/next_tick.js:68:7)
  err.stack;
}

try {
  await Band.find({ _id: badId }).exec();
} catch (err) {
  // With `exec()`, the stack trace includes where in your code you
  // called `exec()`. Below is the stack trace:
  //
  // CastError: Cast to ObjectId failed for value "this is not a valid id" at path "_id" for model "band-promises"
  //   at new CastError (/app/node_modules/mongoose/lib/error/cast.js:29:11)
  //   at model.Query.exec (/app/node_modules/mongoose/lib/query.js:4331:21)
  //   at Context.<anonymous> (/app/test/index.test.js:138:42)
  //   at process._tickCallback (internal/process/next_tick.js:68:7)
  err.stack;
}

Lainnya juga:Permintaan bukanlah janji :

const query = Band.find({name: "Guns N' Roses"});
assert.ok(!(query instanceof Promise));

// A query is not a fully-fledged promise, but it does have a `.then()`.
query.then(function (docs) {
  // use docs
});

// `.exec()` gives you a fully-fledged promise
const promise = query.exec();
assert.ok(promise instanceof Promise);

promise.then(function (docs) {
  // use docs
});



  1. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. Spring Data Mongo - Metode kueri dan bidang Berbeda

  2. Tidak dapat membuat mongoid bekerja dengan Rails 4

  3. praktik terbaik mongodb:bersarang

  4. Bagaimana cara mendapatkan daftar koleksi di luwak?

  5. Bagaimana saya bisa menghapus elemen array bersarang dalam dokumen mongodb dengan driver c#