猫鼬响应奇数格式

时间:2017-04-17 18:15:21

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

我尝试做的是让用户获取他们添加到收藏夹中的帖子列表,只需将他们的_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' } } ]




1 个答案:

答案 0 :(得分: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 });