Docs Home / mongosh / Write Scripts

Script Considerations脚本注意事项

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

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.findOne();
}

// This code will fail此代码将失败
function listEntries() { return db.students.findOne(); }
function* findResults() {
yield listEntries();
}

Use an async generator function instead:请改用异步生成器函数:

function listEntries() { return db.students.findOne(); }
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.这种数组排序方法通常比等效的不受支持的代码性能更高。

JavaScript SettersJavaScript设置器

The following JavaScript setter does not work:以下JavaScript设置程序不起作用:

// This code will fail此代码将失败
class TestClass {
value = 1;

get property() {
return this.value;
}

// does not work:不起作用:
set property(value) {
this.value = db.test.findOne({ value });
}
}