【问题标题】:Node js adding new property to a array of objects when returning from mongoose collection从猫鼬集合返回时,Node js向对象数组添加新属性
【发布时间】:2015-05-28 05:55:51
【问题描述】:

我正在使用 nodejsexpressmongoose 创建应用程序。 mongodb.user 是猫鼬模式模型,我正在尝试获取用户对象数组,该查询是完美的,我的问题是我想为每个用户添加新属性。我已经尝试如下。但它不会添加到集合中。

exports.memberlist = function(req, res) {
        user.find({}).exec(function(err, collection) {
             collection.forEach(function(member){
             member.city  = 'Colombo';
             collection.push(member);
             });
        res.send(collection);
        });
};

【问题讨论】:

  • 你正在推入你正在迭代的集合。是否替换现有项目?
  • 用户收藏中没有名为city的项目。我想添加具有价值的新项目。

标签: node.js mongodb express


【解决方案1】:

你可以这样做

在架构级别创建创建虚拟属性

userSchema.virtual('city').get(function () {
  return 'Colombo';
});

在控制器级别

exports.memberlist = function(req, res,next)
{
  user.find({}).exec(function(err, users)
    {
if(!err)
{
res.json(200, users.toObject({virtual: true}));
}
else
{
next(err);
}

    });
};

【讨论】:

  • 感谢您的回答。但实际上我想通过在循环中查询另一个集合来设置城市元素。
  • 你可以使用 Model.update(conditions, update, options, callback);您可以在选项中设置 multi:true 它会在将任何细化添加到 Schema 字段之前更新所有文档
  • exports.memberlist = function(req, res) { user.find({}).exec(function(err, collection) { collection.forEach(function(member) { subscriptions.find({ member._id},'city', function(err, subscription){ member.city = subscription.city; collection.push(member); }); }); res.send(collection); }); };这里的订阅是另一个猫鼬模型,我想从该特定用户那里获取城市并将其添加到成员对象中。
  • 为什么要使用 collection.push(member)
  • 您正在尝试创建新文档
【解决方案2】:

默认情况下,Mongoose 不允许向从 MongoDB 数据库中提取的对象添加属性。为此,您有两种选择:

1/ before exec statement you add a lean() method : 
user.find({}).lean().exec(function(err, collection) {do whatever you want with collection}

2/ collection = collection.toObject();

【讨论】:

    猜你喜欢
    • 2021-12-18
    • 2016-03-20
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    相关资源
    最近更新 更多