【问题标题】:return single object based on ObjectId根据 ObjectId 返回单个对象
【发布时间】:2018-06-16 21:47:25
【问题描述】:

您好,我目前正在构建一些有趣的东西,允许用户发布任何内容。我在这里遇到一些问题是我的代码。

 return details.findOne({'data': {$elemMatch: {'_id':req.params.id}}}).then((a) => {
            return res.render('post', { a });
        }).catch(err => console.log(err));
我只希望它返回一篇我认为通过使用 objectId id 可以做到这一点的帖子,但它似乎返回数据数组中的所有内容,任何人有任何想法下面是我的架构。

我需要这个只返回 objId 在 url 中的单个对象

    var schemaMode = new mongoose.Schema({
        email: {type: String, required: true},
        password: {type: String, required: true},
        username: {type: String,required:true},
        data: [{
            author: String,
            title: String,
            comments: [String],
            article: String,
        }]
    });

【问题讨论】:

  • 试试return details.find().select({'data': {$elemMatch: {'_id':req.params.id}}}).then((a) => { return res.render('post', { a }); }).catch(err => console.log(err));

标签: javascript node.js database mongodb mongoose


【解决方案1】:
Details.findById(req.params.id, function(err, foundObject){
   //foundObject contains the object with the ._id matching req.params.id
});

如果您只想返回某些字段,例如您希望对象只有其数据字段,那么您可以这样做:

Details.findById(req.params.id, "data",
function(err, foundObject){
   //foundObject contains the object with the ._id matching req.params.id
});

Details.findById(req.params.id).select("data")
.exec(function(err, foundObject){
   //foundObject contains the object with the ._id matching req.params.id
});

需要明确的是,在上面的代码中,Details 是导入的(需要)架构(在您的情况下,是名为 schemaMode 的架构)

【讨论】:

  • 我只希望数据数组中的数据适用于此还是仅适用于电子邮件密码等字段?
  • @seancarroll 是的,它会起作用,我编辑了答案,所以示例是数据字段
  • 似乎无法正常工作我 console.log foundObject 并且它返回 null ?
  • @seancarroll 您是否使用了正确的架构名称?在我的示例中,我使用了带有大写字母的详细信息。在您的代码中,您使用的是“详细信息”,小写 d,保持模式名称与您自己的代码中的名称相同。但如果它已经正确,那么获取 null 意味着 req.params.id 与集合中任何对象的 _id 都不匹配
  • 是的,我使用了正确的模式名称小写,我解决了它,感谢您的帮助:)
【解决方案2】:

“数据”是您的“帖子”吗?如果是这样,我认为你需要一个投影。

    return details.findOne({'data': {$elemMatch: {'_id':req.params.id}}},{'data.$'}).then((a) => {
        return res.render('post', { a.data[0] });
    }).catch(err => console.log(err));

'data.$' 将为您投影整个模型,仅填充所需的“数据”/“帖子”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 2020-08-23
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多