I want to add elements in an array that can contain two different schemas and populate it.
Problem: populate() return an array of ids.
This is what I tried:
const mongoose = require('mongoose');
const { ObjectId } = mongoose.Schema.Types;
const cardSchema = new mongoose.Schema(
{
name: { type: String, required: true },
localDevice: [
{
type: ObjectId,
required: true,
refPath: 'onModel'
}
],
onModel: {
type: ObjectId,
enum: ['location', 'device']
}
},
{ timestamps: true }
);
const cardModel = mongoose.model('card', cardSchema);
module.exports = cardModel;
Insert a new card:
const newCard = new cardModel({
name: "Card 1",
localDevice: ["115b2fe8b7bb5d3d49078a12", "115c1c6fd363f41494e6a714"]
});
await newCard.save();
Populate:
const cards = await cardModel
.find({ userId: mongoose.Types.ObjectId(userId) })
.select({
_id: 1,
name: 1,
localDevice: 1
})
.populate({ path: 'localDevice' });
type or paste code here