本文介绍了当需要另一个文件的架构时,猫鼬填充返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个节点应用程序.用户可以拥有最喜欢的房间列表(就像愿望清单一样).我正在尝试将列表 ID 添加到用户最喜欢的列表中,但这总是未定义.如果我做console.log(users.favoriteListings);"输出变得未定义.请提供任何帮助.

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);

});

推荐答案

您从 mongoose 获得了一组用户.此数组没有 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.

在你的 userController 中,尝试用这个替换 console.log:

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

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

这篇关于当需要另一个文件的架构时,猫鼬填充返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 12:34