Node.js 异步/等待Mongoose集合,为什么不创建我的帖子集合?
我将解释我用这段代码尝试了什么Node.js 异步/等待Mongoose集合,为什么不创建我的帖子集合?,node.js,mongoose,Node.js,Mongoose,我将解释我用这段代码尝试了什么 mongoose.connect('mongodb://localhost/postdb', { useNewUrlParser: true, useUnifiedTopology: true, }).then(() => console.log('Successfully connect to MongoDB.')) .catch((err) => console.error('Connection error', err))
mongoose.connect('mongodb://localhost/postdb', {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => console.log('Successfully connect to MongoDB.'))
.catch((err) => console.error('Connection error', err));
async function createPost() {
try {
const jean = await User.create({
username : 'Jean', email: 'jtigana@aol.com',
});
const c1 = await Comment.create({postedBy : jean, body: 'Enfent terrible' });
await Post.create({title: 'Vou comer voce! ',
body: 'What a wonderful life!',
postedBy: jean,
comments: c1,
});
} catch (err) {
console.log(err);
}
}
createPost();
我的PostSchema
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',
}]
});
我期待3个集合,想法是以后其他用户可以在同一篇文章中添加评论。蒙哥达罗盘
我从终端运行代码
node --trace-warnings --unhandled-rejections=strict index.js
Try/catch block没有抱怨。为什么缺少第三个集合?您已将postedBy和comments声明为ObjectId,但您正在传递一个对象而不是id。请执行以下操作:
await Post.create({title: 'Vou comer voce! ',
body: 'What a wonderful life!',
postedBy: jean.id,
comments: c1.id,
});
现在你通过了两个Id
另外,您已经将post声明为PostSchema,但随后尝试创建一个未声明的post。您应该将Post.create重命名为PostSchema.create,或将PostSchema重命名为Post。我已经查看了,问题是您已将de Post声明为PostSchema,但您是一篇未声明的文章。它应该是PostSchema.create,而不是Post.create.module.exports=mongoose.model('Post',PostSchema);模块导出正常。是否正确导入?我已经复制了你的代码,它将3个集合保存在数据库中。是的,问题是MongoDB Atlas。现在可以正常工作了!