V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
gancl
V2EX  ›  Node.js

mongoose 怎么在子文档的 array 里 update 或 insert?

  •  
  •   gancl · 2014-06-06 16:51:45 +08:00 · 4127 次点击
    这是一个创建于 3895 天前的主题,其中的信息可能已经有所发展或是发生改变。
    //数据库是
    {
    "__v": 1,
    "_id": "538f5f0f6195a184108c8bd8",
    "title": "GameTitle",
    "item": [{
    "_id": "538f5f0f6195a184108c8bd6",
    "name": "itemOne",
    "men": [{
    "_id": "5390cccf0a84f41f37082874",
    "user": "id22222222",
    "score": 2000
    }, {
    "_id": "2390cccf0a84f41f37082873",
    "user": "id33333333",
    "score": 1000
    }]
    }, {
    "_id": "538f5f0f6195a184108c8bd7",
    "name": "itemTwo",
    "men": []
    }],
    "status": 1
    }
    var MenSchema = new mongoose.Schema({
    user: 'String',
    score: {
    type: Number,
    default: 0
    }
    });
    var ItemsSchema = new mongoose.Schema({
    name: String
    ,men: [MenSchema]
    });
    ListsSchema = new mongoose.Schema({
    title: {
    type: String,
    required: true
    }
    ,item: [ItemsSchema]
    });
    var Items = mongoose.model('item', ItemsSchema);
    var Lists = mongoose.model('lists', ListsSchema);
    var Men = mongoose.model('men', MenSchema);
    //代码是: Insert and update:
    function commit(sId, sItem, sUser, sIncreaseScore) {
    Lists.findOne({, "_id": sId,
    "item.name": sItem
    }, null, function(err, documents) {
    if (!err) {
    if (documents != null) {
    Lists.findOne({
    "_id": sId,
    "item.name": sItem,
    "item.men.user": sUser
    }, null, function(err, subDoc) {
    if (!err) {
    if (subDoc != null) {
    //increase user score
    //!!!!!!!!!!!!!But subDoc will get all arrays of item.men, so I can't update it correctly
    } else {
    //inser new user score
    var userData = new Men({
    user: sUser,
    score: sScore
    });
    documents.item[0].men.push(userData);
    documents.save(function(err) {
    if (!err) {
    ///!!!!!!!!!!!!!!Will come this
    console.log("documents error on save!");
    } else {
    console.log("save documents ok!");
    }
    });
    }
    }
    });
    }
    } else {
    console.log("not find the game item!");
    }
    }
    );
    }
    view raw gistfile1.js hosted with ❤ by GitHub



    这是一个类似iOS game center分数排行榜的数据库, 一个游戏里有多个item项目, 每个项目有多个玩家的分数数据.
    document里包含了subDoc子文档,子文档里又有一个array,怎么找到这个array里的某个值,并对它进行修改?
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2201 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 12:44 · PVG 20:44 · LAX 04:44 · JFK 07:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.