【问题标题】:undefined when getting value from mongoose database从 mongoose 数据库获取值时未定义
【发布时间】:2018-09-15 01:33:26
【问题描述】:

对于学校,我必须使用 MEAN 堆栈制作一个有角度的网站。 根据 Insomnia,我的 GET 方法正在 json 对象中返回我的法术和 cmets。

router.get('/API/posts/', function(req, res, next) {
  let query = Post.find().populate("comments").populate("spell");
  query.exec(function(err, posts){
  if(err) { return next(err); }
    res.json(posts);
  });
});

每当我尝试使用我的咒语时,我都会收到undefined。此方法从get 方法中获取我的项目(我得到除了我的咒语之外的所有值)

get posts() : Observable<Post[]> {
return this.http.get(`${this._appUrl}/posts/`)
  .pipe(
    map((list: any[]): Post[] =>
      list.map(Post.fromJSON)
  ));
}

我的 fromJSON 方法:

static fromJSON(json: any): Post {
  const post = new Post(
    json.title,
    json.description,
    json.originalPoster,
    json.category,
    json.spell.map(Spell.fromJSON)
  );
  post._id = json._id;
  post._comments = json.comments;
  return post;
}

在我将咒语添加到我的帖子模块之前,一切正常。找了好久,希望大家能帮帮我就好了

我的架构:

var mongoose = require('mongoose');

var PostSchema = new mongoose.Schema({
  title: String,
  description: String,
  spell: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Spell'
  },
  originalPoster: String,
  category: String,
  dateCreated: { type: Date, default: Date.now },
  comments: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Comment'
  }],
  votes: { type: Number, default: 0 }
}); 
mongoose.model('Post', PostSchema);

【问题讨论】:

  • 也分享你的模式模型。谢谢
  • 我已经添加了我的 PostSchema
  • 该特定帖子可能没有任何拼写。看看这个:stackoverflow.com/questions/38009808/…
  • 我已经修好了。我把地图扔了出去,而是这样做了:new Spell(json.spell.name, json.spell.level, json.spell.castingTime, ect)这似乎很奇怪

标签: angular express mongoose mean-stack


【解决方案1】:

试试populate("comments spell");

【讨论】:

  • 你真的需要扩展这个答案。
猜你喜欢
  • 1970-01-01
  • 2012-04-09
  • 2016-06-23
  • 1970-01-01
  • 1970-01-01
  • 2013-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多