在Mongoose中初始化ref数组

时间:2014-08-22 17:39:20

标签: node.js mongoose

说我有以下架构:

var promoGroupSchema = new Schema({
    title: String,
    offers: [{Schema.Types.ObjectId, ref: 'Offer']
});

var offerSchema = new Schema({
    type: String
});

如何使用新优惠初始化促销组?由于save()是异步的,因此以下工作无效。现在,我知道我可以将一个函数作为保存函数的参数,但是随着更多的优惠而变得丑陋。

var offer1 = new offerSchema({
    type: "free bananas!"
});

var offer2 = new offerSchema({
    type: "free apples!"
});

offer1.save();
offer2.save();

var newPromoGroup = new promoGroupSchema({
    title: "Some title here",
    offers: [offer1._id, offer2._id]
});

从我读到的内容来看,Mongoose一旦你创建它们就给对象一个_id,我可以依赖它们吗?

1 个答案:

答案 0 :(得分:0)

您应该在保存回调中访问_id。如果您有很多要约组的优惠,使用像async这样的库会让您的生活更轻松。

var myOffers = [...]; // An array with offers you want to group together

// Array of functions you want async to execute
var saves = myOffers.map(function(offer) {
    return function(callback) {
        offer.save(callback);
    }
}

// Run maximum 5 save operations in parallel
async.parallelLimit(saves, 5, function(err, res) {
    if(err) {
        console.log('One of the saves produced an error:', err);
    }
    else {
        console.log('All saves succeeded');
        var newPromoGroup = new promoGroupSchema({
            title: "Some title here",
            offers: _.pluck(myOffers, '_id') // pluck: see underscore library
        });
    }
});

你也可以尝试使用Promises。