Express + Mongoose将对象推入对象数组,并在插入时向对象中再添加两行

时间:2015-04-04 10:49:08

标签: node.js mongodb 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(错误)使其可读)。 这就是我现在尝试解决的问题。

  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"

        }]

我该如何解决这个问题?

1 个答案:

答案 0 :(得分: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) {...
  });