findById return as a result the findOne statement

Viewed 26

I am trying to create a wishList , I have created the model :

const mongoose = require("mongoose");
var wishSchema = new mongoose.Schema({
    products:{
        type: Array
    }
});
module.exports = mongoose.model("Wishlists",wishSchema)

Now, I'm trying to find all the elements in the products Array :

const Product = require("../models/Product");
const Wish = require("../models/Wishlists");
let wish = await Wish.findById(user.wishlist);
let  wishpro = wish.products;
console.log(wishpro);//['62dfg6g46hjkkibvvc23']
for(let i = 0; i < wishpro.length ; i++) {
  let x = Product.findById( wishpro[i]);
  console.log("x : " + typeof(x) );//object
  wishProducts.push(x);
}
console.log( "wish : " +wishProducts);//wish : 
findOne({ _id : '62dfg6g46hjkkibvvc23 ' })

The problem is that, x = findOne({_id: '62dfg6g46hjkkibvvc23 '}) is this even possible I really don't understand, what is happening here!

1 Answers

Use populate

let wish = await Wish.findById(user.wishlist).populate({path: 'products'});
console.log(wish.products);
Related