【问题标题】:Display an specific array from a Mongoose schema显示来自 Mongoose 模式的特定数组
【发布时间】:2013-01-14 23:38:18
【问题描述】:

这是我正在使用的架构:

var userschema = new mongoose.Schema({

  user: String,
  pass: String,
  imagen: [{ 

              title: String,
              name: String,
              description: String

});

这就是我正在做的:

usermodel.find({ 'imagen._id': req.params.id }, function (err, imagen){

  user.imagen 

    if(err) throw err;
    console.log(imagen);

    res.send(imagen);

});

我想要接收的只是imagen 数组中的元素,其中_id我正在寻找,但相反,我收到了用户的洞模式,包括他的所有图像。有什么可以只接收我正在寻找的数组对象吗?这是一个例子:

[ { __v: 3, _id: 50f41ccff405ef73c4000006, 通过:'mangakas123', 用户:'kirbo', 图片: [ {标题:'DQ怪物', name: '勇者斗恶龙1and2EnemySpriteGallery_02.png', description: 'DQ怪物合集', _id: 50f41f868e7f9919c7000006 } ], 时间线: [], 通知: [], 追随者:['50f41c8c59ebd50fc4000006'], 关注:[] } ]

我只想要这个:

[{ title: 'DQ monstes',
     name: 'DragonQuest1and2EnemySpriteGallery_02.png',
     description: 'A compilation of DQ monsters',
     _id: 50f41f868e7f9919c7000006 }]

感谢您的提前!

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您可以像这样排除其他字段

    usermodel.find({ 'imagen._id': req.params.id },{'imagen':true}, function (err, imagen){
    
      user.imagen 
    
        if(err) throw err;
        console.log(imagen);
    
        res.send(imagen);
    
    });
    

    查看 find() 的第二个参数:http://docs.mongodb.org/manual/reference/method/db.collection.find/

    【讨论】:

    • 它有效,但不是我所期望的。我得到了image 数组的洞,不仅是我正在寻找的_id 的数组元素,而且,在显示imagen 数组之后,控制台向我显示了这个错误Cannot read property '_id' of null。为什么会发生这种情况? Mongoose 完美地读取了数组,并将其显示在控制台中。
    猜你喜欢
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    相关资源
    最近更新 更多