正在调用Node js-ejs文件中数组中的对象



大家干得好!

我有一个用Node.js编写的项目。在这个项目中,我有一个如下的模式结构。

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,
},
});

我能够从poster成功地将数据添加到这个模式中。但是我不能读取ejs文件中的数据,我该怎么做?

我可以通过控制台读取数据,我在控制台上使用的代码如下:

const debt = await Debt.find({}).populate('medicine.data').sort('-createdAt');
console.log(JSON.stringify(debt[0].medicine[0].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>
<% } %>

但是当我在ejs文件中执行此操作时,它只返回id和quantity值。当我在控制台中打印它时,我可以访问医学模式中的所有数据。为什么我不能访问ejs文件?你能帮我吗?

当我在控制台中打印它时,它返回的数据

{"_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}

当我在ejs上打印它时,它会返回一个类似于的值

{"data":"624e0b3633533f3a31e3dc6a","quantity":2,"_id":"62537484a05359a8cf356fef"}

是的,我刚刚解决了这个问题,我没有通过控制结构正确填充页面。。。也许这种情况可能发生在其他人身上,在这种结构中,有必要在填充过程中发送两个数据。

问题解决方案:

const debt = await Debt.findOne({ _id: req.params.id }).populate('medicine.data');
populate('medicine.data')

我可以说,整个过程都围绕着这里。

最新更新