Docs HomeMongoDB Shell

Script Considerations脚本注意事项

The results of database queries cannot be passed inside the following contexts:数据库查询的结果不能在以下上下文中传递:

  • Class constructor functions类构造函数函数
  • Non-async generator functions非异步生成器函数
  • Callbacks to .sort() on an array回调到数组上的.sort()

To access to the results of database calls, use async functions, async generator functions, or .map().要访问数据库调用的结果,请使用异步函数异步生成器函数.map()

Constructors构造函数

The following constructors do not work:以下构造函数不起作用:

// This code will fail
class FindResults {
constructor() {
this.value = db.students.find();
}
}

// This code will fail
function listEntries() { return db.students.find(); }
class FindResults {
constructor() {
this.value = listEntries();
}
}

Use an async function instead:请改用async函数:

class FindResults {
constructor() {
this.value = ( async() => {
return db.students.find();
} )();
}
}
Note

You can also create a method that performs a database operation inside a class as an alternative to working with asynchronous JavaScript.您还可以创建一个在类中执行数据库操作的方法,作为使用异步JavaScript的替代方法。

class FindResults {
constructor() { }

init() { this.value = db.students.find(); }
}

To use this class, first construct a class instance then call the .init() method.要使用这个类,首先构造一个类实例,然后调用.init()方法。

Generator Functions生成器函数

The following generator functions do not work:以下生成器函数不起作用:

// This code will fail
function* FindResults() {
yield db.students.findMany();
}

// This code will fail
function listEntries() { return db.students.findMany(); }
function* findResults() {
yield listEntries();
}

Use an async generator function instead:请改用async generator function

function listEntries() { return db.students.findMany(); }
async function* findResults() {
yield listEntries();
}

Array Sort数组排序

The following array sort does not work:以下数组排序不起作用:

// This code will fail
db.getCollectionNames().sort( ( collectionOne, collectionTwo ) => {
return db[ collectionOne ].estimatedDocumentCount() - db[ collectionOne ].estimatedDocumentCount() )
} );

Use .map() instead.请改用.map()

db.getCollectionNames().map( collectionName => {
return { collectionName, size: db[ collectionName ].estimatedDocumentCount() };
} ).sort( ( collectionOne, collectionTwo ) => {
return collectionOne.size - collectionTwo.size;
} ).map( collection => collection.collectionName);

This approach to array sort is often more performant than the equivalent unsupported code.这种数组排序方法通常比等效的不受支持的代码更具性能。