简体   繁体   中英

Mongoose Populate returning undefined when requiring schema from another File

I'm making a node application. Users can have favorite Listings of rooms ( just like wish list). I'm trying to add listings ids to user favorite listings but that always gives undefined. if i do "console.log(users.favoriteListings);" the output comes to be undefined. Any help please.

listingModel.js

var mongoose = require("mongoose");
var Schema = mongoose.Schema;//creating schema


var ListingSchema = new Schema({
location: {//ROOM LOCATION
            type: [Number],  // [<longitude>, <latitude>]
            index: '2d'      // create the geospatial index
    },
}
);


var Listing = mongoose.model('Listing', ListingSchema);

module.exports = Listing;

userModel.js

var mongoose = require("mongoose");
var Schema = mongoose.Schema;//creating schema
var Listing=require('../listing/listingModel');


var UserSchema = new Schema({

favoriteListings :  [{ type: Schema.Types.ObjectId, ref: 'Listing' }],


}

);


var User = mongoose.model('User', UserSchema);


module.exports = User;

userController.js

addFavListing:function(req,res){

//READ TOKEN AND FIND USER ID, IF USER HAS REACHED THIS POINT, THIS MEANS THAT TOKEN ALREADY
//HAS BEEN VERIFIED
var token = req.body.token || req.query.token || req.headers['x-access-token'];
var decoded=jwt.verify(token, app.get('superSecret'));
var id=decoded._doc._id;console.log(id);


User.find({_id:id}).populate('favoriteListings').exec(function(err,users) {
  if (err){ return handleError(err);}
    console.log(users.favoriteListings);

});

You got an array of users from mongoose. This array has no favoriteListings property. But each user in the array must have his favoriteListings.

In your userController, try to replace the console.log by this one:

console.log(users.forEach(function(user) {
    console.log(user.favoriteListings);
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM