0
    var SecuritySchema = new Mongoose.Schema({
        _bids: [{
            type: Mongoose.Schema.Types.ObjectId,
            ref: 'BuyOrder'
        }],
        _asks: [{
            type: Mongoose.Schema.Types.ObjectId,
            ref: 'SellOrder'
        }]
    });

    var OrdersSchema = new Mongoose.Schema({
        _security: {
            type: Mongoose.Schema.Types.ObjectId,
            ref: 'Security'
        },
        price: {
            type: Number,
            required: true
        },
        quantity: {
            type: Number,
            required: true
        }
    });


    // declare seat covers here too
    var models = {
        Security: Mongoose.model('Security', SecuritySchema),
        BuyOrder: Mongoose.model('BuyOrder', OrdersSchema),
        SellOrder: Mongoose.model('SellOrder', OrdersSchema)
    };
    return models;

而不是当我保存一个新BuyOrder的例如:

// I put the 'id' of the security: order.__security = security._id on the client-side
var order = new models.BuyOrder(req.body.order);
    order.save(function(err) {
        if (err) return console.log(err);
    });

并尝试重新检索相关的安全性:

models.Security.findById(req.params.id).populate({
        path: '_bids'
    }).exec(function(err, security) {
        // the '_bids' array is empty.
    });

我认为这是某种命名问题,但我不确定,我在这里和moongoose网站上看到了Number用作Id类型的示例:http: //mongoosejs.com/docs/populate.html

4

2 回答 2

0

ref字段应使用单数模型名称

另外,只需执行以下操作:

models.Security.findById(req.params.id).populate('_bids').exec(...

鉴于您目前的代码段,我的主要怀疑是您的req.body.orderhas_security作为字符串而不是包含字符串的数组。

此外,您不需要id财产。Mongodb 本身会自动将其_id作为真正的 BSON ObjectId 执行,而 mongoose 将添加id为相同值的字符串表示,所以不用担心。

于 2013-09-02T18:37:53.063 回答
-1

While I don't understand your schema (and the circular nature of it?), this code works:

var order = new models.BuyOrder({ price: 100, quantity: 5});
order.save(function(err, orderDoc) {
    var security = new models.Security();
    security._bids.push(orderDoc);
    security.save(function(err, doc) {
       models.Security.findById({ _id: doc._id })
           .populate("_bids").exec(function(err, security) {
              console.log(security);

           });
    });
});

It:

  1. creates a BuyOrder
  2. saves it
  3. creates a Security
  4. adds to the array of _bids the new orderDoc's _id
  5. saves it
  6. searches for the match and populates

Note that there's not an automatic method for adding the document to the array of _bids, so I've done that manually.

Results:

{ _id: 5224e73af7c90a2017000002,
  __v: 0,
  _asks: [],
  _bids: [ { price: 100, 
           quantity: 5, 
           _id: 5224e72ef7c90a2017000001, __v: 0 } ] }
于 2013-09-02T19:35:08.490 回答