2017-07-05 37 views
0

我期待創建一個包含ObjectId的動態where子句。無法使用JSON解析將字符串轉換爲ObjectId。字符串到ObjectId使用JSON.parse

這裏是我努力使工作......

var className = 'maths'; 
var studentId = '595d193cd4832d53bfc22cea' 
var where = JSON.parse('{ "class.' + className + '.student":' + studentId + '}') 

College.findOne(where); 

我的where子句應該看看下面和上面的語句應該運行沒有錯誤

{class.math.student: 595d193cd4832d53bfc22cea } 

{class.math.student: ObjectId('595d193cd4832d53bfc22cea') } 

請幫忙

+0

您使用貓鼬,因此,如果您的模式屬性被正確地與'「類型」中定義:Schema.Types.ObjectId'然後貓鼬將* *爲你做這個**,這是首先使用ODM的一部分。如果這沒有發生,那麼你的模式是「不正確的」。在你的問題中顯示你的模式,以便我們糾正你的錯誤。也爲第1000次**「JavaScript對象不是JSON」**。 –

回答

0

您可以建立where對象不用解析字符串:

var ObjectId = require('mongoose').Types.ObjectId; 

var where = { class: {} }; 
where.class[className] = { student: new ObjectId(studentId) }; 
+0

對不起,似乎沒有工作。對象可以作爲where子句傳遞嗎? –

+0

我相信它有效,但有一個「新」缺失(現在增加在一個版本中)。現在試試 :) –

相關問題