Script Considerations脚本注意事项
On this page本页内容
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();
} )();
}
}
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.这种数组排序方法通常比等效的不受支持的代码更具性能。