简体   繁体   English

在Monk中使用fineOne(),find()函数的正确方法

[英]The right way to use fineOne(), find() functions in Monk

I am building an RESTful API using expressjs and Monk. 我正在使用expressjs和Monk构建RESTful API。 There's a requirement where I should grab several documents from different collections (One-to-Many). 我需要从不同的集合中获取多个文档(一对多)。 But I'm not sure how to implement it. 但我不确定如何实现它。

For example, I need to grab one car information from the Cars collection, and 4 wheels from Wheels collection. 例如,我需要从Cars系列中获取一个汽车信息,并从Wheels系列中获取4个车轮信息。 I know that I should use findOne() to find the car, and from there I can access the type of wheels. 我知道我应该使用findOne()来找到汽车,从那里我可以访问这种类型的车轮。

The Code would be something like this 守则将是这样的

var wheelType;
cars.findOne({_id: "C300"}).then((car) => {
  wheelType = car["wheeltype"];
})

Here's the point. 这就是重点。 I now have the car information, but I couldn't define a variable outside of the scope to save the value, and start a new find() function to collet the information for wheels. 我现在有汽车信息,但我无法定义范围之外的变量来保存值,并启动一个新的find()函数来为轮子信息进行collet。

Surely, I can try to do everything in .then() just like this 当然,我可以尝试像这样在.then()中做所有事情

cars.findOne({_id: "C300"}).then((car) => {
  wheels.findOne({type: car["wheeltype"][0] }).then((wheel) => {
    // combind the car with wheel
  })
})

but, what if I have more details to collect? 但是,如果我有更多细节要收集怎么办? do I just nest the findOne() function? 我只是嵌套findOne()函数?

I might be fitting the MySQL idea wrongly to MongoDB (there's some other way to implement the One-to-Many mapping?). 我可能错误地将MySQL思想与MongoDB相匹配(还有其他一些实现一对多映射的方法吗?)。 I am expecting something like this: 我期待这样的事情:

collection cars we have 我们收集的汽车

{
  {
    name:"c300",
    wheeltype:["A","B","C"]
  }
  {
    name:"R100",
    wheeltype:["E","F","C"]
  }
}

collection wheels we have 我们收集轮子

{
  {
    type:"A",
    Brand:"BestWheel"
  }
  {
    type:"C",
    Brand:"GoodWheel"
  }
}

and after the manipulation, I have this as output 在操作之后,我将此作为输出

{
   name:"c300",
   wheel:{
           Brand:"BestWheel",
           type:"A"
          }
}

I find it reasonable to nest the findOne() function since it is an asynchronous call back function. 我发现嵌套findOne()函数是合理的,因为它是一个异步回调函数。 Then for this question if you want to implement something like the requirement, nested is necessary. 那么对于这个问题,如果你想实现类似需求的东西,嵌套是必要的。

cars.finOne(...).then((car) =>{
  wheels.findOne(...).then((wheel) =>{
    // create a json that contains wheels in a car object.
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM