2016-12-15 12 views
0

私はfollwingスキーマを持っている:マングース移入キャストエラー

// online.js 
var mongoose = require('mongoose'); 

// Online Friends 
var onlineSchema = mongoose.Schema({ 
    userid:{ type: Number, ref:'Player' } 
},{timestamps : true}); 


// Export 

module.exports = mongoose.model('Online', onlineSchema); 


//player.js 
var mongoose = require('mongoose'); 

// define the schema for player data 
var playerSchema = mongoose.Schema({ 
    userid : { type: Number, required: true,unique:true, default: 0 }, 
    firstname : { type: String }, 
    nick : {type: String, required: true}, 
    lastname : {type: String}, 
    lastupdate: {type: Date, default: Date.now} 
},{timestamps : true}); 


// create the model and expose it to our app 
module.exports = mongoose.model('Player', playerSchema); 


//main.js 
... 
const Online = require('./config/models/online.js'); 
const Player = require('./config/models/player.js'); 

Online.find({userid:3441341}).populate('userid').exec(function(err,result){ 
    if (err) { 
    console.log(err); 
    } else { 
    console.log(result); 
    } 
}); 

... 

私は私が間違っているのかを正確に確認してください、ではないユーザーIDのためにオンラインで検索し、ユーザーの名前を印刷したいです。 これは私が取得していますエラーです:

MongooseError: Cast to ObjectId failed for value "3441341" at path "_id" 

これを達成するための適切な方法は何ですか?

+0

他のモデルも表示できますか? – Codearts

+0

これらの2つは交差する唯一のものです。 – Trax

答えて

1

ユーザーIDのタイプをNumberからmongoose.Schema.ObjectIdに変更すると正常に動作します。基本的には、あなたはオブジェクトIDに番号をキャストしようとしています。 idsを文字列として渡します。 NoSQL DBSでは、文書に_idフィールドが必要です。あなたはユーザーモデルを持っていますか、または仕事のためにプレーヤーを使用していますか? PlayerをUserモデルとして使用している場合は、user_idを_idに変更してください。

+0

モデル「オンライン」のパス「userid」の値「1299304」でObjectIdへのキャストが失敗しました。私はユーザーIDに番号を指定していますが、型はNumberではありませんか? – Trax

+0

UseridタイプをNumberからmongoose.Schema.ObjectIdに変更しようとしましたか? – Codearts

+0

はい、新しいエラーが発生します。 – Trax

関連する問題