从集合mongodb nodejs中获取随机id



让我首先说,当谈到mongodb时,我是一个全新的人。我正在做一个项目,该项目将客户的数据存储在客户集合中,将手机存储在手机集合中,并将他们在订单集合中做出的订单存储在数据中。订单将只是客户的id和订购的手机的id。我通过从40个数组中插入10个随机条目创建了电话集合。我想做的是打开手机收藏,从那里随机获取一个id,并将其添加到订单中。在直接mongodb中,我使用db.collection('phones').find({}, {manufacturer: 0, model: 0, price: 0});使其工作,它返回一个随机id,并且只返回电话集合中一个电话的id。同样的方法不适用于nodejs。

我曾尝试在节点中使用CCD_5[/code>运行该命令,以获取电话集合中的所有ID,然后尝试操作这些ID,但它返回了一个我无法访问的对象object。我在第一个元素上只尝试了console.log,将其保存到phoneCollection var中,然后尝试phoneCollection[0];结果是没有定义的。

我知道我很可能会在这里犯很多新手的错误,所以如果我没有看到明显的错误,我很抱歉。

作为参考,我使用的函数如下,连接运行良好,并在更高级别的函数调用中打开。这个方法适用于我的其他插入,没问题,我对这个插入有问题。

const insertOrders = function(db, callback){
const collections = db.collection('orders');
console.log("phone test "+db.collection('phones').find({}, {manufacturer: 0, model: 0, price: 0})); 
//this just prints out [object Object]
var phoneCollection = db.collection('phones').find({}, {manufacturer: 0, model: 0, price: 0});
console.log("Phone collection " +phoneCollection);
//same as previous, just wanted to test if assigning
it would be different and also tried 
phoneCollection[0] which comes back undefined.
const phone1 = db.collection('phones').find({}, 
{manufacturer: 0, model: 0, price: 0})
.limit(-1).skip(db.collection('phones').estimatedDocumentCount()*Math.floor(Math.random()))
.next();
console.log("phone one "+phone1);
//this comes back as an [object Promise]
collections.insertMany([
{"customerID": 1,
"phoneOrdered": phone1}, {"customerID": 3, "phoneOrdered" : phone1, "phoneOrdered": phone1},
], function(err, result) 
{
console.log(result);
callback(result);
});
}

任何人如能提供任何见解,我们将不胜感激。

要只获取id,请使用CCD_7:

var phoneCollection = db.collection('phones').find({}, {manufacturer: 0, model: 0, price: 0});
var myDocument = phoneCollection.hasNext() ? phoneCollection.next() : null;
if (myDocument) {
var myID = myDocument._id;
print (tojson(myID));
}

在进行控制台日志使用时,而不是+:

console.log("Phone collection " ,phoneCollection);

最新更新