Mongoose populate returns a null array

Mongoose does not play well with the public. 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);

The database looks right.

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

But when I do the filling, I get an empty array of "books"

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

            if(data){

            }
});

Everything there simply will not be filled. Any suggestions would be greatly appreciated.

0
source share
1 answer

Seems wrong refin userSchema, it should refer to the circuit book, not userthe circuit itself.

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

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

Source: https://habr.com/ru/post/1683154/


All Articles