子文件mongoose中的更新字段

时间:2014-02-26 10:45:23

标签: javascript node.js api mongodb mongoose

我的父母模特

var GameChampSchema = new Schema({
  name: String,
  gameId: { type: String, unique: true },
  status: Number,
  countPlayers: {type: Number, default: 0},
  companies: [
    {
      name: String,
      login: String,
      pass: String,
      userId: ObjectId
    }
  ],
  createdAt: {type: Date, default: Date.now},
  updateAt: Date
})

我需要在没有设置的第一个孩子中插入userId属性

因此,只需对具有条件的父级执行此操作({status:0,countPlayers:{$ lt:10})

2 个答案:

答案 0 :(得分:3)

由于这是一个嵌入式文档,因此很容易:

如果要更新作为数组第一个元素的文档,具有userId

db.collection.update(
    { 
        "status": 0,
        "countPlayers": {"$lt": 10 },
        "companies.userId": {"$exists": false }
    },
    { "$set": {"companies.$.userId": userId } }
)

哪个会很好,但显然这与MongoDB处理逻辑的方式不匹配,并认为如果具有的数组中存在某些,则没有任何内容匹配现场。您可以使用聚合框架获取该元素,但这无助于找到我们需要的位置。

简化提案是阵列中根本没有元素的地方:

db.collection.update(
    { 
        "status": 0,
        "countPlayers": {"$lt": 10 },
        "companies.0": {"$exists": false }
    },
    { "$push": {"userId": userId } }
)

这只是在阵列上放了一个新东西。

对我来说,合乎逻辑的是,您实际上知道有关此条目的内容,而您只想设置userId字段。所以我会在登录时匹配

db.collection.update(
    { 
        "status": 0,
        "countPlayers": {"$lt": 10 },
        "companies.login": login,
    },
    { "$set": {"companies.$.userId": userId } }
)

最后,如果只是更新数组中的第一个元素,那么我们不需要匹配位置,因为我们已经知道它在哪里:

db.collection.update(
    { 
        status: 0, 
        countPlayers: {"$lt": 10 }
    },
    { $set: { "companies.0.userId": userId  } }
)

追溯到我的逻辑案例,请参阅文档结构:

{ 
    "_id" : ObjectId("530de54e1f41d9f0a260d4cd"),
    "status" : 0,
    "countPlayers" : 5,
    "companies" : [ 
        { "login" : "neil" },
        { "login" : "fred", "userId" : ObjectId("530de6221f41d9f0a260d4ce") },
        { "login": "bill" },
     ] 
}

因此,如果您正在寻找的是“没有userId”的第一个文档,那么这没有意义,因为有几个项目并且您已经有特定的 userId进行更新。这意味着你必须表示一个。我们如何判断哪个一个?根据用例,您似乎试图根据您拥有的信息将userId中的信息与之匹配。

逻辑说,查找您知道的key value,并更新匹配的位置

只需用db.collection部分替换您的model对象即可与Mongoose一起使用。

有关相关详细信息,请参阅$exists上的文档以及$set$push

答案 1 :(得分:0)

非常感谢。

我解决了他的问题

exports.joinGame = function(req, res) {
  winston.info('start method');
  winston.info('header content type: %s', req.headers['content-type']);

  //достаем текущего пользователя
  var currentUser  = service.getCurrentUser(req);
  winston.info('current username %s', currentUser.username);
  //формируем запрос для поиска игры
  var gameQuery = {"status": 0, "close": false};
  gameChamp.findOne(gameQuery, {}, {sort: {"createdAt": 1 }}, function(error, game) {
    if (error) {
      winston.error('error %s', error);
      res.send(error);
    }
    //если игра нашлась
    if (game) {
      winston.info('Append current user to game: %s', game.name);
      //добавляем userId только к одной компании
      var updateFlag = false;
      for (var i=0; i<game.companies.length; i++) {
        if (!game.companies[i].userId && !updateFlag) {
          game.companies[i].userId = currentUser._id;
          updateFlag = true;
          winston.info('Credentials for current user %s', game.companies[i]);
          //если пользовател последний закрываем игру и отправляем в bw, что игра укомплектована
          if (i == (game.companies.length-1)) {
            game.close = true;
            winston.info('game %s closed', game.name);
          }
        }
      }
      //сохраняем игру в MongoDB
      game.save(function(error, game) {
        if (error) {
          winston.error('error %s', error);
          res.send(error);
        }
        if (game) {
          res.send({ game: game })
          winston.info('Append successful to game %s', game.name);
        }
      });
    }
  });
}
相关问题