【问题标题】:how to create a document in a mongodb collection and update another collection in the same time如何在 mongodb 集合中创建文档并同时更新另一个集合
【发布时间】:2012-10-07 09:39:12
【问题描述】:

这是我的问题

我有三个架构

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({


})

需要注册用户模式才能使用应用程序,但无需注册商店模式,除非用户想卖一些东西。但是,当用户注册 shopschema 时,我需要使用商店的 _id 更新用户模式,

这就是我所做的

  1. 在商店集合中创建文档
  2. 找到商店_id
  3. 更新用户集合

你可以看到我查询数据库三次,所以我想知道这是否可以在一个查询中完成以节省时间

Shop.create(regist_data,function(){
    //update the user collection here
})

以防万一你想知道我为什么需要这个,因为我使用“护照”登录用户,并且我想通过 req.user 中商店的 _id 访问 ProductShcema,否则每次我想访问 ProductShcema我想找到商店的_id,然后得到属于商店的_id的产品。

如果你有更好的解决方案,请告诉我。谢谢!!!

【问题讨论】:

    标签: session mongodb mongoose


    【解决方案1】:

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

    这是我想出来的

    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);
     })
    })
    

    它创建商店文档并更新用户集合,它适用于我。

    【讨论】:

      猜你喜欢
      • 2019-09-18
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-17
      相关资源
      最近更新 更多