繁体   English   中英

从集合 mongodb nodejs 中获取随机 id

[英]Get random id from collection mongodb nodejs

首先让我说我对 mongodb 完全陌生。 我正在开发一个项目,该项目将客户数据存储在客户集合中,电话集合中的电话以及他们在订单集合中的订单。 订单将只是客户的 ID 和订购的电话的 ID。 我通过从 40 个数组中插入 10 个随机条目来创建电话集合。我要做的是调用电话集合并从那里获取一个随机 id 并将其添加到订单中。 在直 mongodb 我让它工作使用db.phones.find({}, {manufacturer: 0, model: 0, price: 0}).limit(-1).skip(db.phones.count()*_rand()).next() 它返回一个随机 id,并且只返回一个电话集合中一部电话的 id。 同样的方法不适用于 nodejs。

我尝试使用在节点中运行命令db.collection('phones').find({}, {manufacturer: 0, model: 0, price: 0}); 获取手机集合中的所有 id,然后尝试操作这些,但它返回 object Object 我无法访问。 我在第一个元素上尝试了 console.log,将它保存到 phoneCollection var 然后尝试 phoneCollection[0]; 结果是未定义的。

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

作为参考,我正在使用的 function 如下所示,连接运行良好,并在 function 调用中打开。 此方法适用于我的其他插入没问题,这是我遇到问题的插入。

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,请使用select

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM