2016-08-26 108 views
0

工作,我已經在userref.js貓鼬找到不的ObjectId

module.exports = (function userref() { 

    var Schema = mongoose.Schema; 

var newSchema= new Schema([{ 

     userId: { 
      type: mongoose.Schema.Types.ObjectId, 
      ref: 'User', 
      index: true 
     }, 
       value: { type: Number } 

    }]); 

    var results = mongoose.model('UserRef', newSchema); 

    return results; 

})(); 

定義一個架構我已經插入了一些數據,當我嘗試獲取一些數據,我從MongoDB的控制檯獲取正確的價值觀

db.getCollection('userrefs').find({'userId':ObjectId('57a48fa57429b91000e224a6')}) 

它正確返回一些數據

現在的問題是,當我嘗試通過給OBJECTID我得到空數組中的代碼來獲取一些數據。在下面的功能userrefs返回爲空數組

//req.params.userId=57a48fa57429b91000e224a6 
var UserRef = require('../userref.js'); 
this.getuserref = function (req, res, next) { 

     try { 
      var o_userId =mongoose.Types.ObjectId(req.params.userId); 
      var query = { userId: o_userId }; 
      var projection = '_id userId value'; 

      UserRef.find(query, projection, function (err, usrrefs) { 
       if (err) return next(err); 
       res.send(usrrefs); 
       console.log("userref fetched Properly"); 
      }); 
     } catch (err) { 
      console.log('Error While Fetching ' + err); 
      return next(err); 
     } 
    }; 

此外,當我調試的代碼,我可以看到o_​​userId爲OBJECTID與值id一些垃圾字符

o_userId: ObjectID 
_bsontype: "ObjectID" 
id: "W¤¥t)¹â$¦" 
+0

是否需要用戶id的一份文件中的數組?或每個文檔一個userId? –

+0

我從代碼 – anand

+0

得到emty數組你有沒有嘗試過,因爲貓鼬在你的內部爲你做了'var query = {userId:req.params.userId};'? – chridam

回答

0

添加出口這樣

module.exports.modelname= mongoose.model('userrefs', nameofschema, 'userrefs');  

var z = require('../userref.js'); 

var UserRef = z.modelname; 

現在使用UserRef調用。

只是簡單地嘗試這個人。

Model.find({ 'userId': objectidvariable}, '_id userid etc', function (err, docs) { 
     // docs is an array 
    }); 

從他們的官方文檔複製的參考樣本。

+0

如何在req.params.userid – anand

+0

objectidvariable中的字符串中創建objectidvariable很適合用字符串格式。只需傳遞字符串格式的實際對象標識即可。像'123ahehadh13123h' =這是我的對象ID例如。簡單地'var objectidvariable ='12312313asdad';' –

+0

@ Alien01我發現了這個問題,我想這不是關於查詢本身,而是關於如何查詢。 –

0

試試這個:

try { 
     var o_userId =mongoose.Types.ObjectId(req.params.userId); 
     var query = { userId: o_userId }; 
     var projection = '_id $.userId $.value'; 

     UserRef.find(query, projection, function (err, usrrefs) { 
      if (err) return next(err); 
      res.send(usrrefs); 
      console.log("userref fetched Properly"); 
     }); 
    } catch (err) { 
     console.log('Error While Fetching ' + err); 
     return next(err); 
    } 
+0

它仍然給空陣列 – anand

+0

嘗試''userId「:o_userId'而不是'userId:o_userId' –

+0

試過這也:(不工作 – anand