[英]How to create nested object with Mongoose ref connection?
我正在尝试从另一个 Object 中获取 map 数据,并在 MongoDB 上创建新数据。
我有这样的视频架构
const videoSchema = new mongoose.Schema({
video_id: {
type: String,
required: true,
unique: true
},
author: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Author'
}
})
和作者架构
const authorSchema = new mongoose.Schema({
author_id: {
type: String,
required: true,
unique: true
},
avatar: {
type: String,
required: true,
}
})
现在我像这样创建 Object 并保存到数据库
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)
}
})
视频数据保存成功。 但是作者的数据没有保存在数据库中。 有什么问题以及如何以正确的方式保存所有数据?
代码看起来还好吗? 我看到保存部分不太好,我不知道如何改进它。
谢谢
化繁为简,按顺序一一保存。
避免将async/await
与.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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.