使用 _.each 将动态 属性 添加到 Mongoose 结果
Add a dynamic property to a Mongoose result with _.each
我想为 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 don't allow adding properties. You need to either call the 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);
});
我想为 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 don't allow adding properties. You need to either call the 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);
});