我正在處理一個特定的簡單案例。我需要一些幫助,因爲我似乎無法找到解決方案。[Mongoose] [Node.js]插入後找不到文檔
我在javascript類中爲MongoDB創建了一個簡單的Schema和Model。
this.UserSchema = new this.Schema({
UserId: { type: String },
IsToggle: { type: Boolean}
});
this.CalendarViewUserSchema = new this.Schema({
_id: { type: this.Schema.ObjectId },
OwnerId: { type: String },
UserList: [ this.UserSchema ]
});
this.CalendarViewUser = this.mongoose.model('CalendarViewUsers',this.CalendarViewUserSchema);
這是在構造函數中,我已經有很多數據庫交互工作,但我無法設法讓這個工作。
我把這種方法用於添加新文檔:
AddCalendarViewUser : function(Id, UserToAddId){
NewUser = { UserId : UserToAddId, IsToggle : false };
this.CalendarViewUser.update(
{ OwnerId : Id },
{
$set: { OwnerId : Id },
$push: { UserList : NewUser }
},
{upsert:true},
function(err){
if(err) {console.log(err);}
else {console.log('Success');}
}
);
}, // this comma just introduces the next method.
這工作得很好。我可以看到使用Mongo Explorer正確創建了文檔,並且如果使用.find()從集合中檢索所有內容,它就會顯示出來。
於是,我試圖尋找與插入的文件:
FindCalendarViewUser : function(Id){
this.CalendarViewUser.findOne(
{ OwnerID : Id },
function(err,result){
if(err) {console.log(err);}
else{console.log(result);}
}
);
}
這裏,返回結果= NULL。
兩個方法中的「Id」參數都是一個字符串,就像架構中的「OwnerId」一樣。
我在做什麼錯?
「OwnerId」和「Id」都相同。我也嘗試將兩者都轉換爲ObjectId,但沒有成功。
對不起,我的代碼格式。
編輯:
基本上,我可以使用_id領域找到文件:
{ _id : '4fb0d1702edfda0104fc2b9f'}
但我不能與OWNERID領域找到它:
{ OwnerId : '4f55e1a6c2c7287814000001'}
這些值直接從數據庫中取得,因此它們對應於實際存儲的值。
編輯2:
我想通了,如果我用手工插入值:
$set: { OwnerId : '4f55e1a6c2c7287814000001' }
,然後由完全相同的搜索字符串,它返回的文件!
this.CalendarViewUser.findOne(
{ OwnerID : '4f55e1a6c2c7287814000001'}
...
所以我想它是將一些垃圾的種類在文檔的OWNERID場,或有某種同場的類型不兼容。我會公佈結果。
對我的反饋延遲抱歉,它確實是一個錯字。我正在測試的文件上的console.log是正確的。我把這個錯字寫在這裏。 任何想法爲什麼會發生這種情況?你記得這種坐姿的絆腳石嗎? 謝謝。 –
如果我使用「_id」字段作爲搜索參數,我找到該文檔。如果我使用由我創建的OwnerId字段,它不會找到任何內容。 我嘗試使用與ObjectId類型的領域OwnerId沒有運氣。 –
我也嘗試手動插入搜索查詢,如下所示: {OwnerID:'4f55e1a6c2c7287814000001'}(這是該字段中的Id,因爲我可以在Mongo Explorer中看到) –