在Mongoose中,您可以编写如下语句来返回带有受限字段的文档,其中只有10个受限字段.这将每次返回相同的10个文档,这是意料之中的.
products = await Product.find({
category: category,
})
.select("title img price desc category postageCost")
.limit(10);
我想在页面加载上显示random products,而Mongoose .sample()
方法是完美的,所以我写了以下内容:
products = await Product.find({
category: category,
})
.select("title img price desc category postageCost")
.sample(10);
不过,我似乎不能让它像我预期的那样工作.相反,我必须运行Product.find().sample(10)
,然后修改返回的对象,只返回"TITLE IMG PRICE DEC CATEGORY postageCost"字段.
可以用Mongoose组合select()
和sample()
吗?或者我的方法是返回随机字段并限制返回文档内容的唯一方法吗?