2017-02-12 59 views
0

说我有以下数组:节点Q环和追加daata

[{id: 1, name: 'Hello', otherTableId: 2}]; 

现在,我经历了所有这些阵列的希望循环,并从我的MongoDB的一些数据,我要附加到一个新的数组,然后返回。

我该怎么做q

这里是我到目前为止,但我不知道是什么,以取代foreach有:

router.route('/api/conversations') 
.get(function (req, res) { 
    mongoose.models.conversation.find({users: {$all: [req.query.id]}}, function (err, conversation) { 
     if (err) { 
      res.status(500).send(err) 
     } 
     else { 
      var returnArray =[]; 
      conversation.forEach(function (x) { 

      }) 
     } 
    }); 
}); 

我的模式

var conversation = mongoose.Schema({ 
    users: Array 
}); 

var user = mongoose.Schema({ 
    username: String, 
    password: String, 
    firstname: String, 
    lastname: String, 
    is_active: Boolean, 
    user_type: Number 
}); 

什么,我想回到basicly是名单对话和他们的用户。

像这样:[{conversation_id: String, userOne: Object, userTwo: Object}]

但林不知道这是可能的吗?

回答

1

首先,在猫鼬你建在人口逻辑,这意味着你应该能够加入这样的事情:

conversation 
.find({users: {$all: [req.query.id]}) 
.populate('otherTableId') 
.exec(function (err, conversations) { 
    // now the convesations array should have followed the link from 'otherTableId' if you have defined the ref in the schema. 
}) 

如果我解释我想你问的这个问题更通用Promise库Q应该支持Promise.all方法。我正在使用下面的标准ES6实现,但请随时在Q中找到相应的方法。

const ids = [1,2,3,4] 
const promises = ids.map(id => mongoose.models.childTable.findOne(id)) 
Promise.all(promises).then(array => { 
    // here you will find the array containing the objects 
}) 
+0

嘿,基督教,感谢您的回复。我添加了一些更多的代码基础,也许你可以看看? –

+0

对话架构应该包含用户架构的引用。在查询对话时,您应该使用填充来直接包含用户对象。请看一下这个页面了解正在发生的事情: http://mongoosejs.com/docs/populate.html –

+0

它具有用户架构的引用,但是以阵列形式 –