Let me start by saying I am completely new when it comes to mongodb. I'm working on a project which stores data for customers in a customers collection, phones in a phones collection and orders they have made in an orders collection.
The orders will just be the id of the customer and the id of the phones ordered.
I have created the phones collection by inserting 10 random entries from an array of 40.
What I'm trying to do is call on the phones collection and take a random id from there and add it to the order.
In straight mongodb I got it to work using
db.phones.find({}, {manufacturer: 0, model: 0, price: 0}).limit(-1).skip(db.phones.count()*_rand()).next()
which returns a random id and only an id for one of the phones in the phone collection. This same approach doesn't work with nodejs.
I have tried running the command in node using
db.collection('phones').find({}, {manufacturer: 0, model: 0, price: 0});
to get all the ids in the phones collection and then try manipulate these but it returns an object Object which I can't access. I've tried just console.log on the first element saving it to a phoneCollection var then trying phoneCollection[0]; and it comes out undefined.
I am aware I am very likely making many rookie mistakes here so sorry if I'm not seeing the obvious.
For reference, the function I'm using is below, the connection is running fine and opened in a function call higher up. This method works for my other inserts no problem, it's this insert I'm having issues with.
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);
});
}
Any insights anyone can help with would be greatly appreciated.