Node.js 如何使用异步/等待语法填充我的模型?
我读过很多类似的帖子,大部分都是关于回调的例子。我正在尝试创建一条评论并将其添加到我的帖子中Node.js 如何使用异步/等待语法填充我的模型?,node.js,mongoose,Node.js,Mongoose,我读过很多类似的帖子,大部分都是关于回调的例子。我正在尝试创建一条评论并将其添加到我的帖子中 const Post = require('./models/Post'); const Comment = require('./models/Comment'); const newLocal = 'mongodb://localhost/postdb'; mongoose.connect(newLocal, { useNewUrlParser: true, useUnifiedT
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',
}]
});
比约森邮报
{ "_id" : ObjectId("5fa13e1523e71045227bf74d"), "comments" : [ ObjectId("5fa13e1523e71045227bf74c") ]
已创建评论,但未将其添加到帖子中。如何以正确的方式指定路径?您可以使用
findOneAndUpdate()
。在您的情况下,它将找到帖子并使用commentId更新帖子。
我假设您的Post模式与此类似-
const mongoose=require('mongoose'))
const PostSchema=新的mongoose.Schema({
标题:字符串,
正文:字符串,
创建数据:{
类型:日期,
默认值:Date.now,
},
邮寄人:{
类型:mongoose.Schema.Types.ObjectId,
ref:'用户',
},
评论:[{
类型:mongoose.Schema.Types.ObjectId,
参考:“评论”,
}]
});
module.exports=PostSchema
const Post=require('./models/Post');
const Comment=require(“./models/Comment”);
康斯特纽尔酒店mongodb://localhost/postdb';
mongoose.connect(新本地、{
useNewUrlParser:true,
useUnifiedTopology:正确,
})。然后(()=>console.log('成功连接到MongoDB'))
.catch((err)=>console.error('Connection error',err));
异步函数readP(){
试一试{
const comment=wait comment.create(
{标题:'Boa tarde',
正文:“Adriana bonita”,
postedBy:mongoose.Types.ObjectId(“5f96e440f47c1d211e84d712”)
});
const post=wait post.findOne({title:'BJohnson'})
const commentId=post.comments | |【】//获取帖子的所有注释Id
commentId.push(comment.id)//将新的注释id推送到现有注释id的
const updatedPost=wait Post.findOneAndUpdate({title:'BJohnson'},{comments:commentIds})。填充({path:'comment'});
}捕捉(错误){
控制台日志(err);
}
}
readP();
看看我的模式。对,因为注释是一个数组。因此,首先我们必须获取所有注释,然后将新注释Id推送到它,然后使用findOneAndUpdate
。我已经更新了我的代码。让我知道它是否有效。只有身份证,没有头衔,没有尸体。我不明白你上面说的。