2016-11-28 86 views
1

我有兩個模式一個是user.js的文件,用戶模式等是product.js產品架構文件如何訪問一個模型架構在另一個模型貓鼬數據庫

在user.js的文件我的用戶架構如下:

var userSchema = new Schema({ 
    firstname: { 
     type: String, 
     required: true 
    }, 
    lastname: { 
     type: String, 
     required: true 
    }, 
    password: { 
     type: String, 
     required: true 
    }, 
    mobileno: { 
     type: Number, 
     unique: true, 
     required: true 
    }, 
    facebookid: { 
     type: String 
    }, 
    userimage: { 
     type: String 
    } 
}); 

,我_id用貓鼬,自動遞增模塊來獲取用戶集合中自動增加用戶id中重寫自動生成。

而在product.js我的產品架構文件如下:

var productSchema = new Schema({ 
    userId: { 
     type: String, 
     required: true 
    }, 
    productName: { 
     type: String, 
     required: true 
    }, 
    productId: { 
     type: String, 
     required: true 
    }, 
    price: { 
     type: Number, 
     unique: true, 
     required: true 
    }, 
    prodcutImage: { 
     type: String 
    } 
}); 

當用戶將集合添加新的產品,他將填補在產品架構中提到的所有領域。我想在產品收集中用戶添加新產品時,驗證用戶收藏中是否存在輸入的用戶ID。 我試圖訪問userSchema.find方法productSchema預先保存勾

productSchema.pre('save', function (next) { 
    userSchema.findOne({'_id': userId}, function(err, user) 
    { 
     console.log(user); 
    }); 
} 

但它返回一個錯誤。有人可以幫我解決這個問題。

+0

路由器級中間件是什麼錯誤? – sidgate

+1

看到正確的錯誤和帖子..我的想法是什麼意思。 –

回答

2

你可以這樣做

app.get('/user/:id', function (req, res, next) { 
     userSchema.findOne({'_id': userId}, function(err, user) 
    { 
     if(user){ 
      next() 
       }else{ 
        res.json("user id is not valid"); 
        } 
    });  
    }, function (req, res, next) { 
     // code to add your product in product schema 
    }) 

更多更好的辦法是使用快遞

+0

快遞路由器級中間件是一個很好的替代品! –

相關問題