V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐工具
RoboMongo
推荐书目
50 Tips and Tricks for MongoDB Developers
Related Blogs
Snail in a Turtleneck
gancl
V2EX  ›  MongoDB

mongoose 怎么 populate 别的集合的子文档?

  •  1
     
  •   gancl · 2014-06-13 15:49:09 +08:00 · 4763 次点击
    这是一个创建于 3904 天前的主题,其中的信息可能已经有所发展或是发生改变。
    ASchema = new mongoose.Schema({
    name: String,
    B: [BSchema]
    });
    var BSchema = new Schema({
    name: String
    });
    var CSchema = new Schema({
    name: String,
    B: {
    type: Schema.ObjectId,
    ref: 'BSchema'
    }
    });
    //This is OK, but not one time mongoose search:
    CSchema.find({
    name: 'C_xxx'
    }).exec(function(err, docC) {
    docC.forEach(function(o) {
    var BId = o.B;
    ASchema.findOne({
    'B._id': BId
    }, {
    'B.$': 1
    }
    ).exec(function(err, docA) {
    var Bname = docA.B[0].name;
    var Cname = docA.name;
    });
    });
    });
    //wrong in populate:
    CSchema.find({
    name: 'C_xxx'
    })
    .populate('ASchema.B')
    .exec(function(err, docC) {
    docC.forEach(function(o) {
    var Bname = o.B.name;
    //ERROR:o.B is a objectId,o.B.name is undefined
    //Aname can't find
    });
    });
    /*
    Data like this:
    ASchema = {
    name: "A_xxx",
    B: [{
    _id: 1,
    name: "B_xxx"
    }, {
    _id: 2,
    name: "B_xxx"
    }]
    }
    CSchema = [{
    name: "C_xxx",
    B: 1
    }, {
    name: "C_xxx",
    B: 2
    }]
    */
    view raw gistfile1.js hosted with ❤ by GitHub

    I can't find it with populate, o.B is a objectId,o.B.name is undefined.

    BSchema is a subdocument of ASchema, CSchema has a ref connection of BSchema.

    I want to find all CSchema which CSchema's name is "c_xxx", and shows CSchema's B's name and its A's name.

    Like this result: {CName:"c_xxx",BName:"b_xxx",AName:"a_xxx"}
    2 条回复    2014-06-13 23:21:27 +08:00
    shuson
        1
    shuson  
       2014-06-13 16:42:57 +08:00
    when populate fields, it only works if there is ref to children from the parent schema
    gancl
        2
    gancl  
    OP
       2014-06-13 23:21:27 +08:00
    @shuson 看来这种情况用不了populate,只能手动一条条查了.
    怎么等待CSchema.find({ 执行完毕? 我再手动将结果构造成json
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1000 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 20:24 · PVG 04:24 · LAX 12:24 · JFK 15:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.