我将解释我在这段代码中尝试了什么
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个集合,想法是以后其他用户可以在相同的帖子中添加评论。MongoDB指南针

我从终端运行我的代码
node --trace-warnings --unhandled-rejections=strict index.jsTry/catch块没有抱怨。为什么第三个集合丢失了?
发布于 2020-10-27 02:03:55
您已经将postedBy和注释声明为ObjectId,但您传递的是一个对象,而不是id。执行以下操作:
await Post.create({title: 'Vou comer voce! ',
body: 'What a wonderful life!',
postedBy: jean.id,
comments: c1.id,
});现在,您正在传递这两个Id。
此外,您已经将帖子声明为PostSchema,但随后您尝试创建一个未声明的帖子。您应该将Post.create重命名为PostSchema.create,或将PostSchema重命名为Post。
https://stackoverflow.com/questions/64542105
复制相似问题