我有一个类似父文档的模式是User,子文档是batchSchema。我的架构在这里
var batchSchema = new Schema({
batchname: {
type: String,
required: true,
unique: true
},
activityname: {
type: String,
required: true
},
time: {
type:String,
required:true
},
duration: {
type:String,
required:true
},
classtype: {
type:String,
required:true
},
trainer: {
type:String,
required:true
},
price:{
type:Currency,
required:true,
unique:true
},
}, {
timestamps: true
});
var User = new Schema({
username:String,
firstname:String,
lastname:String,
password:String,
batches:[batchSchema]
});
当我想在没有batchSchema详细信息的情况下在id的帮助下查看用户的详细信息然后打印两者。它的代码是
router.get('/:userId',function (req, res, next) {
User.findById(req.params.userId, function (err, user) {
if (err) throw err;
res.json(user);
});
});
你可以看到我问题的例子。
{
"_id": "58c66ed333a2171acc603481",
"username": "joe",
"firstname": "jain",
"lastname": "jam",
"__v": 1,
"batches": [
{
"updatedAt": "2017-03-13T10:06:48.341Z",
"createdAt": "2017-03-13T10:06:48.341Z",
"batchname": "rock",
"activityname": "fit",
"time": "1:30pm",
"duration": "175min",
"classtype": "demo",
"trainer": "boby",
"price": "4568",
"_id": "58c66f3833a2171acc603482"
}
]
}
那么,我想知道如何只打印没有子文档的父文档?
答案 0 :(得分:0)
根据Mongoose documentation,你只需要添加第二个参数来指定应该返回哪个字段
router.get('/:userId', function (req, res, next) {
User.findById(req.params.userId, {"batches": 0}, function (err, user) {
if (err) throw err;
res.json(user);
});
});