mongoose populate ObjectId类型数据查询不出来
发布于 2 年前 作者 poorEnMe 1360 次浏览 来自 问答

users:

let UserSchema = new mongoose.Schema({ name:{ unique:true, type:String }, password:String, salt:String }); let user = mongoose.model(‘users’,userSchema);

数据

{ "_id" : ObjectId(“59f88e4e1e1fe314aea326d0”), “salt” : “$2a$12$xTnNVEDgEeafGhJCrGKZ6e”, “name” : “q12345”, “password” : “$2a$12$xTnNVEDgEeafGhJCrGKZ6eK7T4cYDd7S6v0uuiy7iIB8z7XTmPSRy”, "__v" : 0 }

entries

let EntriesSchema = new mongoose.Schema({ userId:{ type:mongoose.SchemaTypes.ObjectId, rel:‘users’ }, body:String, }); let Entries = mongoose.model(‘Entries’,entriesSchema);

数据

{ "_id" : ObjectId(“59f88ea0b322ff14ea6602ff”), “userId” : ObjectId(“59f88e4e1e1fe314aea326d0”), “body” : “asdadadad”, "__v" : 0 }

问题:使用populate怎么都是null

Entries.find() .populate(‘userId’,‘name’) .exec(function (err,entries) { if(err) return next(err); console.log(entries); res.render(‘index’,{ entries:entries }) }); [ { _id: 59f88ea0b322ff14ea6602ff, userId: null, body: ‘asdadadad’, __v: 0 } ]

3 回复

userId:{ type:mongoose.SchemaTypes.ObjectId, rel:‘users’ } ref?

楼上正解是 ref

= =谢谢!!! 卧槽

回到顶部