简体   繁体   中英

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

I am building an RESTful API using expressjs and Monk. 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. I know that I should use findOne() to find the car, and from there I can access the type of wheels.

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.

Surely, I can try to do everything in .then() just like this

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?

I might be fitting the MySQL idea wrongly to MongoDB (there's some other way to implement the One-to-Many mapping?). 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. 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.
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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