Good work everyone!
I have a project that I wrote with Node js. In this project, I have a schema structure as follows.
const debt = new Schema({
name: {
type: String,
required: true,
},
medicine: [{
data: {
type: Schema.Types.ObjectId,
ref: 'Medicine',
},
quantity: {
type: Number,
default: 1
}
}],
total: {
type: Schema.Types.Decimal128,
default: 0,
},
status: {
type: String,
required: true,
},
createdAt: {
type: Date,
default: Date.now,
},
});
const medicine = new Schema({
name: {
type: String,
unique: true,
required: true,
},
price: {
type: Schema.Types.Decimal128,
required: true,
},
medicineType: {
type: String,
required: true,
},
description: {
type: String,
required: true,
trim: true,
},
image: {
type: String,
},
createdAt: {
type: Date,
default: Date.now,
},
});
I am able to successfully add data to this schema from postman. But I can't read the data in the ejs file, how can I do that?
I can read the data through the console and the code I use on the console is as follows:
const debt = await Debt.find({}).populate('medicine.data').sort('-createdAt');
console.log(JSON.stringify(debt[0].medicine[0].data));
The above code successfully returns both the schema it references and its own data.
<% for(let i=0; i< debt.medicine.length; i++) { %>
<input type="checkbox" id="<%= medicine[i]._id%>" name="medicine" checked value="<%= debt.medicine[i].data%>">
<label for="<%= medicine[i]._id%>"><%= JSON.stringify(debt.medicine[i].data) %> - Select %> </label>
<% } %>
But when I do this in the ejs file, it only returns the id and quantity values. When I print it in the console, I can access all the data as in the medicine schema. Why can't I access the ejs file? can you help me?
The data it returns when I print it in the console
{"_id":"624e0b3633533f3a31e3dc6a","name":"Arveles","price":{"$numberDecimal":"19"},"medicineType":"Pill","description":"Medicine","image":"/uploads/1649281846287-medicine1.jpeg","createdAt":"2022-04-06T21:50:46.294Z","__v":0}
When I print it on ejs it returns a value like this
{"data":"624e0b3633533f3a31e3dc6a","quantity":2,"_id":"62537484a05359a8cf356fef"}
Yes, I just solved the situation, I did not correctly populate the page through the control structure... Maybe it may happen to others, in such structures, it is necessary to send two data inside the populate process.
Solution to the problem:
const debt = await Debt.findOne({ _id: req.params.id }).populate('medicine.data');
populate('medicine.data')
I can say that the whole process revolves here.