猫鼬填充返回空数组 [英] mongoose populate returns null array

查看:76
本文介绍了猫鼬填充返回空数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

猫鼬在人口中的表现并不理想.这是我的模特

Mongoose isnt playing very well with population. this is my model

var mongoose = require('mongoose'),
Schema = mongoose.Schema;

mongoose.connect(process.env.MONGO_URI);

var userSchema = new Schema({
  username: String,
  password: String,
  books: [{type: Schema.Types.ObjectId, ref: 'User'}]
  }
);

var bookSchema = new Schema({
  bookid: {type:String, unique:true, required:true},
  imgURL: String
});

module.exports.user = mongoose.model('User', userSchema);
module.exports.book = mongoose.model('Book', bookSchema);

数据库看起来正确.

{ "_id" : ObjectId("56a17cd70a498fcc37cdbe60"), "username" : "test", "password" : "test", "books" : [ ObjectId("56a17d21d43dc32a3a9837de"), ObjectId("56a17ee5d43dc32a3a9837e4"), ObjectId("56a17f5dd43dc32a3a9837e6"), ObjectId("56a17f9fd43dc32a3a9837e8") ], "__v" : 4 }

但是当我进行填充时,会得到一个空的'books'数组

But when I do a populate I get an empty 'books' array

users.findOne({'_id':userid}).populate('books').exec(function(err,data){
            if (err) return console.error(err);

            if(data){

            }
});

所有内容都不会被填充.任何建议将不胜感激.

Everything is there it simply will not populate. Any suggestions would be greatly appreciated.

推荐答案

userSchema中的ref似乎不正确,它应该引用book模式而不是user模式本身.

It seems the incorrect ref in the userSchema, it should reference to book schema rather than user schema itself.

var book = mongoose.model('Book', bookSchema);

...
books: [{type: Schema.Types.ObjectId, ref: 'book'}]

这篇关于猫鼬填充返回空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆