【问题标题】:Mongoose save embedded child and update to other table猫鼬保存嵌入的孩子并更新到其他表
【发布时间】:2016-01-20 16:51:46
【问题描述】:

我有一个如下架构,业务逻辑是这样的: 用户添加一个新的产品类别和多个产品(这将与他们添加到嵌入子项中的新类别相关联),它将保存在下面的架构中。同时,已经添加的产品类别ref会更新给用户

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var ProductSchema = new Schema({
    productname: {
        type: String,
        default: '',
        trim: true
    },
    productprice: {
        type: Number,
        default: 0.00
    }
});

var ProductCategorySchema = new Schema({
    categoryname: {
        type: String,
        default: '',
        trim: true
    },
    categorytype: {
        type: String,
        default: '',
        trim: true
    },
    product: [ProductSchema],
    user: {
        type: Schema.ObjectId,
        ref: 'User'
    }
});

var UserSchema = new Schema({
    name: {
        type: String,
        default: '',
        trim: true
    },
    productCategory: [{
        type: Schema.ObjectID,
        ref: 'ProductCategory'
    }]
});

mongoose.model('ProductCategory', ProductCategorySchema);
mongoose.model('User', UserSchema);

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    首先,通过name找到user的信息,然后把这个user_id赋值给product.user,保存这个product。成功保存此product 后,将product._id 推送到user.productCategory。然后最终保存这个user。示例代码如下。

    //1. create new ProductCategory
    var pc = new ProductCategorySchema({....});
    
    //2. add products into productCategory
    pc.product.push({productname: 'p1', productprice: 10});
    pc.product.push({productname: 'p2', productprice: 11});
    
    User.findOne({name: 'u1'}, function(err, user) {
        if (err)
           // error handling
    
        //3. assign user._id to pc, then save pc
        pc.user = user._id;
        pc.save(function(err) {
            if (err)
               // error handling
    
            //4. push pc._id into this user
            user.productCategory.push(pc._id);
            user.save(function(err) {
                  // ....
            });
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2015-04-10
      • 2017-11-01
      • 1970-01-01
      • 2012-04-16
      • 2017-10-05
      • 2012-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多