Session 如何在mongodb集合中创建文档并同时更新另一个集合

Session 如何在mongodb集合中创建文档并同时更新另一个集合,session,mongodb,mongoose,Session,Mongodb,Mongoose,这是我的问题 我有三种模式 var UserSchema = new Schema({ username:String, email:String, hashed_password:String, salt:String, shop_id:{type:Schema.Types.ObjectId,ref:'Shop'}, }) var ShopSchema = new Schema({ owner_id

这是我的问题

我有三种模式

var UserSchema = new Schema({
        username:String,
        email:String,
        hashed_password:String,
        salt:String,
        shop_id:{type:Schema.Types.ObjectId,ref:'Shop'},
})

var ShopSchema = new Schema({
       owner_id:{type:Schema.Types.ObjectId,ref:'User'},        
       owner_real_id:String,                                    
       owner_real_name:String,                                  
       owner_real_location:String,                              

       shop_name:String,
       sell_product_ids:[Schema.Types.ObjectId],

})

var ProductSchema = new Schema({


})
必须注册userschema才能使用该应用程序,但没有必要注册shopschema,除非用户想要销售一些东西。但是,当用户注册shopschema时,我需要使用商店的_id更新userschema

这就是我所做的

  • 在商店集合中创建文档
  • 找到商店
  • 更新用户集合
  • 正如你所看到的,我查询了数据库三次,所以我想知道是否可以通过一次查询来节省时间,比如

    Shop.create(regist_data,function(){
        //update the user collection here
    })
    
    以防你想知道我为什么需要这个,因为我使用“passport”登录用户,并且我想通过req.user中的店铺id访问产品SCEMA,否则每次我想访问产品SCEMA时,我都会找到店铺id,然后获得属于店铺id的产品


    任何方式,如果你有更好的解决方案,请让我知道。thanx

    对不起,我想我应该更仔细地阅读猫鼬文件

    以下是我的答案

    Shop.create(regist_data,function(err,shop){
        console.log('shop = '+shop);
        User.findByIdAndUpdate(req.user.id,{ $set: { shop_id: shop._id }},{new:true},function(err,data){
      if(err){
        console.log(err)
      }
      console.log('new user = '+data);
     })
    })
    
    它创建了商店文档并更新了用户集合,这对我很有用