2015-04-04 53 views
0

我想在数组对象中添加一个用户,并在插入时再添加两行。Express + Mongoose将对象插入对象数组,并在插入时向对象添加两行更多信息

这些是使用的两个猫鼬模型。

module.exports = mongoose.model('Users', { 

     id:String, //the same id as user.id 
     nick:String, //the same nick as user.nick 

    }); 


module.exports = mongoose.model('Stores', { 

    id: String, 
    user: [{ 
    id: String, 
    nick: String, 
    nr: Number, 
    earnings: Number 
    }], 
    total: Number 

}); 

所以我们假设我想插入一个用户,它的id(不是自动生成的)。 (我已经删除了if(err)以使其可读)。 这是我现在尝试解决的问题。

Users.findOne({id : req.body.userid }, function(err, user) { 

    //what user contains 
    user = { _id: 551fb0b688eacdf0e700000c, 
     id: '123abc', 
     nick: 'Foo', 
     __v: 0 } 

//I want to add this into the user and push it into exsisting array of   
objects that is 'users' 
//But before that i want to add more info to the user, 

//the desired format that I want to insert into 'users' 
user = {id: '123abc', 
     nick: 'Foo', 
     nr: req.body.nr, //new 
     earnings: req.body.earnings} //new 

    Stores.update({id: req.params.id}, 
     {$push: { 'users' : user }}, function(err, store) { 



    }); 

}); 


The current result is the following. 
users: [ 
     { 
      id: "123abc", 
      nick: "Foo" 

     }] 

我该如何解决这个问题?

回答

2

模式设计至少会产生一个问题。如果用户更新他们的nick会怎么样?您不仅需要更新Users集合,还需要更新Stores中与用户匹配的每个文档。您可以使用ref,然后populate来消除这种担忧。

module.exports = mongoose.model('Users', { 
    id: String, //the same id as user.id 
    nick: String, //the same nick as user.nick 
}); 

module.exports = mongoose.model('Stores', { 
    id: String, 
    users: [{ 
    user: { 
     type: mongoose.Schema.Types.ObjectId, 
     ref: 'Users' 
    }, 
    nr: Number, 
    earnings: Number 
    }], 
    total: Number 
}); 

现在查询是:

Users.findOne({ 
    id: req.body.userid 
}, function(err, user) { 
    Stores.update({ 
    id: req.params.id 
    }, { 
    $push: { 
     'users': { 
     user: user, 
     nr: req.body.nr, //new 
     earnings: req.body.earnings 
     } 
    } 
    }, function(err, store) {}); 
}); 

后来,当你需要查询Stores

Stores 
    .find(QUERY) 
    .populate('users') 
    .exec(function(err, stores) {... 
    });