【问题标题】:Ho do I retrieve parent document by its id without sub document in nodejs application? [duplicate]如何在 nodejs 应用程序中通过其 id 检索父文档而没有子文档? [复制]
【发布时间】:2017-08-03 09:05:13
【问题描述】:

我有一个模式,比如父文档是用户,子文档是 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"
    }
  ]
}

那么,我想知道如何只打印父文档而不打印子文档?

【问题讨论】:

    标签: node.js mongodb mongoose schema database


    【解决方案1】:

    根据Mongoosedocumentation,只需要添加第二个参数来指定应该返回哪个字段

    router.get('/:userId', function (req, res, next) {
        User.findById(req.params.userId, {"batches": 0}, function (err, user) {
            if (err) throw err;
            res.json(user);
        });
    });
    

    【讨论】:

    • 也可以用"-batches"代替{"batches": 0}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多