简体   繁体   中英

How to create nested object with Mongoose ref connection?

I'm trying to map data from another Object and create new data on MongoDB.

I have Video schema like this

const videoSchema = new mongoose.Schema({
    video_id: {
        type: String,
        required: true,
        unique: true
    },
    author: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'Author'
    }
})

and Author schema

const authorSchema = new mongoose.Schema({
    author_id: {
        type: String,
        required: true,
        unique: true
    },
    avatar: {
        type: String,
        required: true,
    }
})

now I create Object like this and save to DB

const videoData = getDataForVideo(requestVideoURL)
        .then(resp => {
            const videoObj = resp.item
            return {
                video_id: videoObj.id,
                author: new Author({
                    author_id: videoObj.author_user_id.toString(),
                    avatar: videoObj.author.avatar,
                }),
            }
        })

await videoData.then(resp => {
        const video = new Video(resp)
        try {
            video.save()
                .then(video => {
                    res.status(201).send({ video })
                })
                .catch(err => {
                    res.status(400).send(err.message)
                })
        } catch (error) {
            res.status(400).send(error)
        }
    })

The data of the video saved successfully. But data of the Author is not saved on DB. What is the problem and how to save all data in the right way?

And is the code look ok? I see the saving part is not quite good, I'm not sure how to improve it.

Thank you

Make it simple, save one by one in order.

Avoid mixing async/await with .then/.catch

try {
  const resp = await getDataForVideo(requestVideoURL);
  const videoObj = resp.item;
  const author = new Author({
      author_id: videoObj.author_user_id.toString(),
      avatar: videoObj.author.avatar,
  });

  // save author
  await author.save();

  const video = new Video({
    video_id: videoObj.id,
    author: author.author_id, // ref
  });

  // save video
  await video.save();

  res.status(201).send({ video })
} catch (err) {
  res.status(400).send(err.message)
}

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