我在mongodb中收集了一些文章。我选择了一篇要渲染的文章,并且我想随机选择另外两篇文章。我想在我的收藏中挑选两篇不一样的文章,并且不是我之前选择的文章。 在这个问题上研究了几个小时,寻找解决方案,但只找到了如何随机选择一个元素,但除了一个之外......
这是我现在拥有的:
article.find({}, function(err, articles{
var articleChosen = articles.filter(selectArticleUrl, articleUrl)[0];
article.find({})
.lean()
.distinct("_id")
.exec(function(err, arrayIds){
var articleChosenIndex = arrayIds.indexOf(articleChosen._id);
arrayIds.splice(articleChosenIndex, 1);
chooseRdmArticle(arrayIds, function(articleRdm1Id){
var articleRmd1 = articles.filter(selectArticleId, articleRdm1Id)[0];
var articleRdm1Index = arrayIds.indexOf(articleRdm1Id);
arrayIds.splice(articleRdm1Index, 1);
chooseRdmArticle(arrayIds, function(articleRdm2Id){
var articleRmd2 = articles.filter(selectArticleId, articleRdm2Id)[0];
// do stuff with articleChosen, articleRmd1 and articleRmd2
})
})
})
})
其中选择rdm文章的函数是:
function chooseRdmArticle(articles, callback){
var min = Math.ceil(0);
var max = Math.floor(articles.length);
var rdm = Math.floor(Math.random() * (max - min)) + min;
callback(articles[rdm])
}
从 url 中选择文章的函数是:
function selectArticleUrl(element){
return element.url == this
}
我的想法是处理包含所有 ObjectId 的数组(此处为 arrayIds),在删除 articleChosen
id 后随机选择两个 Id。但我知道 arrayIds.indexOf(articleRdm1Id);
无法工作,因为 ObjectIds 不是字符串...有没有一种方法可以找到我想要的 Id 的索引?或者有更好的主意吗?
非常感谢!
最佳答案
运行两个查询,第一个查询获取所选文档,另一个使用聚合框架运行带有 $sample
的管道。 运算符从集合中返回 2 个随机文档(所选文档除外)。
以下查询使用 Mongoose 的内置 Promises
来证明这一点:
let chosenArticle = article.find({ "url": articleUrl }).exec();
let randomArticles = article.aggregate([
{ "$match": { "url": { "$ne": articleUrl } } },
{ "$sample": { "size": 2 } }
]).exec();
Promise.all([chosenArticle, randomArticles]).then(articles => {
console.log(articles);
});
关于node.js - Mongoose 获取除一个之外的随机元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46401141/