我有这个函数,我在其中检索对象数组,然后有一个for循环遍历对象,并向其附加索引或ind属性:
module.exports.getCustomers = async (req, res) => {
let customers = await Customers.find({}, { "_id": 1 });
for (var i = 0; i < customers.length; i++) {
customers[i].ind = i;
}
console.log(customers)
}
但是当我运行它时,数据返回为
[
{ _id: ... },
{ _id: ... },
...
]
代替:
[
{_id: ..., ind: 0},
{_id: ..., ind: 1},
...
]
请如何解决此问题
答案 0 :(得分:2)
更改您的for
并将其变成map
module.exports.getCustomers = async (req, res) => {
let customers = await Customers.find({}, { "_id": 1 });
let mappedCustomers = customers.map((customer, index) => {
customer['ind'] = index;
return customer;
});
console.log(mappedCustomers);
return mappedCustomers;
}
或者代替返回客户,您可以创建一个全新的客户。
let mappedCustomers = customers.map((customer, index) => {
return {...customer, ind: index};
});
答案 1 :(得分:0)
看来您的对象已冻结,这是您正在使用的库从数据源中提取这些项目的方法,但是您可以在此处https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
了解有关对象冻结的信息。答案 2 :(得分:0)
尝试使用Object.assign
将值复制到各个目标对象。
module.exports.getCustomers = async(req, res) => {
let customers = await Customers.find({}, {
"_id": 1
});
for (var i = 0; i < customers.length; i++) {
Object.assign(customers[i], {
ind: i
});
}
console.log(customers);
}
答案 3 :(得分:0)
我终于解决了。我认为mongoose
搞砸了。但是添加._doc
似乎已经解决了
for (let i = 0; i < customers.length; i++) {
let customer = customers[i],
customer._doc = {
...customer._doc,
index: i
};
}
答案 4 :(得分:-2)
您只需替换
customers[i].ind = i;
收件人
customers[i]['ind'] = i;
或者您可以使用前面提到的Object.assign