嗨我正在构建一些有趣的东西,允许用户发布任何内容。我在这里遇到一些问题是我的代码。
return details.findOne({'data': {$elemMatch: {'_id':req.params.id}}}).then((a) => {
return res.render('post', { a });
}).catch(err => console.log(err));

我需要这个只返回oblId在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,
}]
});

答案 0 :(得分:0)
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
});
OR
Details.findById(req.params.id).select("data")
.exec(function(err, foundObject){
//foundObject contains the object with the ._id matching req.params.id
});
要清楚,在上面的代码中,Details是导入的(带有require)模式(在你的例子中,名为schemaMode的模式)
答案 1 :(得分:0)
是"数据"你的"帖子"?如果是这样,我认为你需要一个投射。
return details.findOne({'data': {$elemMatch: {'_id':req.params.id}}},{'data.$'}).then((a) => {
return res.render('post', { a.data[0] });
}).catch(err => console.log(err));
'数据$'将为您推荐整个模型,仅填充所需的"数据" /" post"