【问题标题】:how to call the data of a schema which is inside another schema(mongodb)如何调用另一个模式(mongodb)中的模式的数据
【发布时间】:2021-12-13 13:47:34
【问题描述】:

我有在用户架构中的练习架构。我需要通过查找UserId来调用userschema的所有用户数据和excersise schema的所有数据字段,除了一个字段。我做了如下。

我的架构,

  const exerciseSchema = new Schema({
  description: String,
  duration: Number,
  date: Date
});

const Exercise = mongoose.model("Exercise", exerciseSchema);

const userSchema = new Schema({
  username: { type: String, unique: true },
  logs: [exerciseSchema]
});
const User = mongoose.model("User", userSchema);

我的 API,

app.get("/api/users/:_id/logs", (req, res) => {
 

  let _id = req.params._id;
  User.findById(_id, (err, data) => {
    if (!err) {
      data.count = data.logs.length;
      res.json({
        username: data.username,
        _id: data._id,
        count: data.count,
        log: data.logs
        
      })
      
    
      }
  
               })
})        
          
     

我的回报应该如下。

{
  username: "test",
  count: 1,
  _id: "5fb5853f734231456ccb3b05",
  log: [{
    description: "test",
    duration: 60,
    date: "Mon Jan 01 1990",
  }]
}

但我的回报低于

    {
"username":"imangi",
"_id":"61795a3f15a4944e134393a4",
"count":3,"log":[{"description":"tennis",
"duration":30,
"date":2021-03-15T00:00:00.000Z,
"_id":"61795a5315a4944e134393a6"}
]}

我需要做的就是摆脱 Id 并将日期转换为本地格式。因为我还是一个学习者,所以我对此有点陌生。有人可以帮忙吗?

【问题讨论】:

    标签: node.js mongodb api express


    【解决方案1】:

    我可以理解您的问题,如果您不需要登录 id 来回复。

    您可以简单地按照以下方式进行操作。通过使用删除

    const array = [
      {
        id: "dsdsd",
        description: "test",
        duration: 60,
        date: "Mon Jan 01 1990",
      },
      {
        id: "abcd",
        description: "test",
        duration: 60,
        date: "Mon Jan 01 1990",
      },
    ];
    
    const newArray = array.map(function (item) {
      delete item.id;
      return item;
    });
    console.log(newArray);
    

    这样做的结果是,

    [
      { description: 'test', duration: 60, date: 'Mon Jan 01 1990' },
      { description: 'test', duration: 60, date: 'Mon Jan 01 1990' }
    ]
    

    所以我们可以像这样绑定在一起。

    app.get("/api/users/:_id/logs", (req, res) => {
      let _id = req.params._id;
      User.findById(_id, (err, data) => {
        if (!err) {
          data.count = data.logs.length;
    
          const modifiedLogs = data.logs.map(function (item) {
            delete item.id;
            return item;
          });
          res.json({
            username: data.username,
            _id: data._id,
            count: data.count,
            log: modifiedLogs,
          });
        }
      });
    });
    

    *** 请注意。可能还有很多其他方法。

    【讨论】:

      猜你喜欢
      • 2020-04-17
      • 2014-08-14
      • 1970-01-01
      • 2016-03-18
      • 2021-12-10
      • 2015-05-18
      • 1970-01-01
      • 1970-01-01
      • 2015-05-15
      相关资源
      最近更新 更多