gpt4 book ai didi

javascript - 使用 _.each 向 Mongoose 结果添加动态属性

转载 作者:可可西里 更新时间:2023-11-01 10:28:55 26 4
gpt4 key购买 nike

我想为 Mongoose 结果的每个对象动态添加一个属性,但它不会按预期工作。

Font.find()
.exec(function (err, fonts) {

if(err) return res.send(err);

_.each(fonts, function(item, i) {
item.joined_name = item.name + item.style.replace(/\s/g, '');
console.log(item.joined_name); // works fine
});

res.send(fonts); // `joined_name` property is nonexistant
});

一定很简单,但我不明白为什么。欢迎使用替代方案!

最佳答案

Mongoose documents 不允许添加属性。您需要调用 lean() exec() 之前的方法,因为启用精益选项的查询返回的文档是纯 javascript 对象。

来自文档:

Font.find().lean().exec(function (err, docs) {
docs[0] instanceof mongoose.Document // false
});

所以你的代码应该是这样的:

Font.find()
.lean()
.exec(function (err, fonts) {
if(err) return res.send(err);

_.each(fonts, function(item, i) {
item.joined_name = item.name + item.style.replace(/\s/g, '');
console.log(item.joined_name); // works fine
});

res.send(fonts);
});

或者将返回的文档转换为普通对象:

Font.find()
.exec(function (err, docs) {
if(err) return res.send(err);
var fonts = [];
_.each(docs, function(item, i) {
var obj = item.toObject();
obj.joined_name = obj.name + obj.style.replace(/\s/g, '');
console.log(obj.joined_name);
fonts.push(obj);
});

res.send(fonts);
});

关于javascript - 使用 _.each 向 Mongoose 结果添加动态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29963412/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com