node.js - 如何使用 async/await 语法填充我的模型?
问题描述
我读过很多类似的帖子,大部分例子都是回调。我正在尝试创建评论并将其添加到我的帖子中。
const Post = require('./models/Post');
const Comment = require('./models/Comment');
const newLocal = 'mongodb://localhost/postdb';
mongoose.connect(newLocal, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => console.log('Successfully connect to MongoDB.'))
.catch((err) => console.error('Connection error', err));
async function readP() {
try {
const comment = await Comment.create(
{title : 'Boa tarde',
body: 'Adriana bonita',
postedBy : mongoose.Types.ObjectId("5f96e440f47c1d211e84d712")
});
const post = await Post.findOne({ title: 'BJohnson'}).
populate( {path : 'comment'},
);
} catch (err) {
console.log(err);
}
}
readP();
后模式
const PostSchema = new mongoose.Schema({
title: String,
body: String,
createdAt: {
type: Date,
default: Date.now,
},
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
comments: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment',
}]
});
B约翰逊邮报
{ "_id" : ObjectId("5fa13e1523e71045227bf74d"), "comments" : [ ObjectId("5fa13e1523e71045227bf74c") ]
评论已创建,但未添加到帖子。如何以适当的方式指定路径?
解决方案
您可以使用findOneAndUpdate()
. 在您的情况下,它将找到 Post 并使用 commentId 更新 Post。我假设您的 Post Schema 看起来与此有些相似 -
const mongoose = require('mongoose')
const PostSchema = new mongoose.Schema({
title: String,
body: String,
createdAt: {
type: Date,
default: Date.now,
},
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
comments: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment',
}]
});
module.exports = PostSchema
const Post = require('./models/Post');
const Comment = require('./models/Comment');
const newLocal = 'mongodb://localhost/postdb';
mongoose.connect(newLocal, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => console.log('Successfully connect to MongoDB.'))
.catch((err) => console.error('Connection error', err));
async function readP() {
try {
const comment = await Comment.create(
{title : 'Boa tarde',
body: 'Adriana bonita',
postedBy : mongoose.Types.ObjectId("5f96e440f47c1d211e84d712")
});
const post = await Post.findOne({ title: 'BJohnson'})
const commentIds = post.comments || [] // get all the comment Id's of the post
commentIds.push(comment.id) // Push the new comment id to existing comment Id's
const updatedPost = await Post.findOneAndUpdate({ title: 'BJohnson'}, {comments: commentIds}).populate({path : 'comment'});
} catch (err) {
console.log(err);
}
}
readP();
推荐阅读
- firebase - (Firebase 的 Firestore || Flutter)如何获取文档中所有地图中相同字段的总数
- hyperledger-fabric - 关于教程的问题:使用 IBM Blockchain VS Code 扩展增强并添加查询到商业票据智能合约
- android - 如何使用“AndroidKeyStore”提供程序生成唯一的 rsa 密钥对(2048)?
- javascript - 如何在单页canvasjs php中有多个图表
- javascript - D3.js 将饼图转换为频谱显示的方法
- android - 移动调整大小元素的最佳方式?
- php - 新手试图在没有运气的情况下抓取网站
- scala - 尝试将函数传递给一个值,但函数运行
- networking - 将网络划分为 4 个子网 - 卡住
- tensorflow - 关于 tensorflow.contrib.eager.metrics.Mean() 的错误