在 Mongoose 的 forEach 循环中添加属性 [英] Adding Properties in a forEach Loop in Mongoose

查看:45
本文介绍了在 Mongoose 的 forEach 循环中添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的帖子数组中的每个帖子都有两个属性名称和编号.所以它就像

lets say each post in my posts array has two properties name and number. so its something like

var posts = [{name:"hey", number: 1}, {name:"foo", number:"2"}]

Javascript 允许我像这样在 foreach 循环中更改这些属性:

Javascript allows me to change these properties in foreach loop like this:

posts.forEach(function(post){
    post.name = "bar"
});

我的数组变成:

var posts = [{name:"bar", number: 1}, {name:"bar", number:"2"}]

但它不允许我添加一个新的属性,如:

but it doesnt allow me add a new property like:

posts.forEach(function(post){
    post.adress = "bar"
});

我的对象保持不变.有没有办法在javascipt的foreach循环中添加属性

my object stays the same. Is there a way to add properties in a foreach loop in javascipt

这是在回调中使用猫鼬发生的..

this is happening using mongoose inside a callback..

  Post.pagination(options, function(err, posts) {
    if (err) console.log(err)
    posts.forEach(function(post){
      post.votetype = 1;
    });
    console.log(posts);
    res.send({ posts : posts  })
  })

在没有添加这个votetype属性之后

after this votetype property is not added

推荐答案

问题是从 Mongoose 返回的数据是不可变的.下面的代码未经测试,但应该会提示您如何使数据可变并对其进行修改.

The problem is that data returned from Mongoose is immutable. The code below is untested but should give you a hint on how to make the data mutable and modify it.

关键是在要修改的 Mongoose 文档对象上调用 toObject().

The key point is calling toObject() on the Mongoose document object you wish to modify.

Post.pagination(options, function(err, posts) {
  if (err) console.log(err);

  var resultPosts = posts.map(function(post) {
    var tmpPost = post.toObject();

    // Add properties...
    tmpPost.votetype = 1;

    return tmpPost;
  });

  console.log(resultPosts);
  res.send({ posts : resultPosts  });
});

这篇关于在 Mongoose 的 forEach 循环中添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆