我正在制作节点应用程序。用户可以拥有最喜欢的房间列表(就像愿望清单一样)。我正在尝试将列表ID添加到用户喜欢的列表,但总是给出undefined。如果我做“console.log(users.favoriteListings);”输出未定义。请帮忙。
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);
});
答案 0 :(得分:0)
你有一群来自mongoose的用户。 此数组没有favoriteListings属性。 但是数组中的每个用户都必须拥有自己喜欢的Listings。
在你的userController中,尝试用这个替换console.log:
console.log(users.forEach(function(user) {
console.log(user.favoriteListings);
}));