how to set a key,value in a mongo array

时间:2016-04-15 15:09:13

标签: arrays node.js mongodb

I have a collection of students where they can have other students as friends

{name:'someone', email:'st', friends[ObjectId,ObjectId]}

To access the list of friends I'll have to populate that object and search inside all the objects of the array friends this will take mutch time

What I would like to do is this:

collection.find({name:'someone'},function(err,obj){
  if(obj['user1'])
    //do st
  else
    //do st
})

this will reuire that i insert objects like this:

collection.find({name:'st'},function(err,obj){
  obj.friends['some one']=ObjectId(of an other student)
})

but this last one is not working

1 个答案:

答案 0 :(得分:0)

如果您使用Mongoose以外的Mongo,则可以轻松完成此操作。在您的学生模式中,您需要一个朋友阵列,这将是其他学生的ID:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var StudentSchema = new Schema({
  name: String,
  friends: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Student' }]
});

module.exports = mongoose.model('Student', StudentSchema);

然后在添加朋友时,您需要做的就是将该朋友的ID推送到朋友阵列中。

一旦集合正确存储了关系,您可以使用mongoose's populate方法实际填写API端点中的数据。这样的事情:

app.get('/student/:id, function(req, res){
    Student.find({_id: req.params.id})
    .populate('friends')
    .exec(function(err, student){
    if(err){
     // handle error
    } else {
       res.json(student)
    }
   }) 

});