0

I have an Collection Model that has a property of items that holds an array of Item Models.

const CollectionSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    items : [{type : mongoose.Schema.Types.ObjectId, ref: 'Item'}]
});

I tried to populate the items array in order to get the objectId's properties, but the items array would return back empty. (The code below is how I populated the items array. I first found the collection I was looking for by the _id using the req.body.search. I then ran .populate("items") in order to populate the items array. What I got back was an empty items array.)

userRouter.post('/iList', passport.authenticate('jwt', {session: false}), (req, res) => {
    Collection.findById({_id : req.body.search}).populate("items").exec((err, document) => {
        if(err)
            res.json(err)
        else
            res.json({item: document})
    })
});

I know my items array isn't empty since I can check on mongoDB that it is full. The image of my mongoDB collection with an items array that isn't empty.

The weird thing is that if I put "collections" into the .populate params, my Items array does return with stuff, but it only returns the ObjectIDs and not actual object properties. I am confused to why .populate("items") isn't working.

2 Answers 2

0

If you are using findById then why are you specifying {_id: req.body.search}. If your req.body.search is a type of mongoose ObjectId string then you can directly use findById(req.body.search) instead of that. Also you can use simply the projection. Second argument in find calls are projections

If you are trying get items array only then why don't you try this query:-

Collection.findById(req.body.search, {items: 1}).then((result) => {
   console.log('Items are :-\n', result);
}, (err) => {
   console.log(err);
})

1 means include and 0 means exclude. So items will be present in output, also _id is default in output. In case you want to exclude _id then you can change second parameter to this -> {items: 1, _id: 0}

Sign up to request clarification or add additional context in comments.

1 Comment

This does work but again the result logs out an array of objectIDs and not object properties. I want to see the object properties instead of objectIDs.
0

Never mind. The issue was when I pushed the Item Models via mongoose, I forgot to do items.save() which meant the items array held nothing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.