Mongoose 给遍历对象添加属性后通过 console.log 不显示
发布于 9 年前 作者 zhuzhichao 4221 次浏览 最后一次编辑是 8 年前 来自 问答

使用的是 keystone 框架。 查询数据后,使用 _.map() 遍历分页结果并给每个结果添加一个处理后的属性

通过 console.log(item) 出来的结果中找不到添加的属性,但是 console.log(item.url) 却能得到值。 大家有没有遇到这样的情况,类似这样的情况如何处理

  Artwork.paginate({
    page: req.query.page || 1,
    perPage: perPage,
    maxPages: maxPages
  })
    .where('createdBy', locals.data.user.id)
    .sort('-updatedAt')
    .exec(function (err, results) {
      results.results = _.map(results.results, function(item) {
        item.url = cloudinary.url(item.photo.public_id, {width: 270, crop: 'fit'});
		console.log(item);
		console.log(item.url);
        return item;
      });
      res.json(results);
    });
4 回复

请问这个问题你解决了吗?我也遇到这个问题了

是不是schema约束的问题

mongoose拿到的其实是它自己的对象,需要转换一下变成普通object才可以进行编辑 比如item = item.toJSON()

monggose里面有个方法lean,链式调用的时候在最后lean一下就可以了 find().lean(),或者find({},{},{lean:true}),原生的mongodb有toArray和toObject方法,用法同lean。请叫我雷锋

回到顶部