【问题标题】:mongoose response odd format猫鼬响应奇数格式
【发布时间】:2017-09-13 09:36:18
【问题描述】:

我想要做的是让用户获得他们添加到收藏夹的帖子列表,只需将他们的 _id 放入帖子的收藏夹数组即可。

当运行该特定查询时,它会以数组的形式返回,其中包含未命名的条目以及数组中的 _locals。

我需要更像 Posts: [ {}, {} ], _locals 的东西。

我怎样才能把它变成那种格式?

var UserSchema = new Schema({
    username  : String,
    firstName : String,
    lastName  : String,
    email     : String,
    password  : String
});

var PostSchema = new Schema({
    author    : { type: Schema.Types.ObjectId, ref: 'User' },
    date      : Date,
    body     : String,
    username  : String,
    sid       : String,
    views     : Number,
    likes     : [{ type: Schema.Types.ObjectId, ref: 'User' }],
    favorites : [{ type: Schema.Types.ObjectId, ref: 'User' }]
});

and the get

app.get('/favorites', function(req, res) {
  Post
  .find({ 'favorites': '58f4f9e5650785228016287f'})
  .exec(function(err, favorites) {
    res.render('favorites', favorites)
    console.log(favorites)
  })
});

I get a response of 
[ { _id: 58f4f9e96507852280162880,
    author: 58f4f9e5650785228016287f,
    body: 'test',
    date: 2017-04-17T17:22:49.059Z,
    username: 'test',
    sid: 'BJ-xquGRl',
    __v: 2,
    favorites: [ 58f4f9e5650785228016287f ],
    likes: [] },
  { _id: 58f500edd8abc7242c90d61c,
    author: 58f4f9e5650785228016287f,
    body: 'w00p w00p',
    date: 2017-04-17T17:52:45.612Z,
    username: 'test',
    sid: 'BJ8g-tG0e',
    __v: 1,
    favorites: [ 58f4f9e5650785228016287f ],
    likes: [] },
  _locals: { user:
     { id: 58f4f9e5650785228016287f,
       username: 'test',
       firstName: 'test',
       lastName: 'test',
       email: 'test@test.com' } } ]

【问题讨论】:

    标签: mongodb express mongoose mongodb-query mongoose-schema


    【解决方案1】:

    _locals 是 Express 添加到您传递给 res.render() 的对象的内容。如果您反转您所做的函数调用,它将不再存在:

    console.log(favorites);
    res.render('favorites', favorites);
    

    但是,主要问题是您将数组 (favorites) 作为参数传递给 res.render(),而它需要一个对象。调用它的正确方法是将favorites 作为对象值传递:

    res.render('favorites', { favorites : favorites });
    // Or in recent Node versions:
    // res.render('favorites', { favorites });
    

    【讨论】:

      猜你喜欢
      • 2016-05-05
      • 2013-05-15
      • 1970-01-01
      • 2012-12-26
      • 1970-01-01
      • 2018-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多