如何在MongoDB中添加2个引用到单个模型?

我正在开发一个博客网站(如中等),其中将有一个用户模型,博客模型和类别模型。 基本思想是将用户存储在用户数据库中,博客数据库中的所有博客和类别数据库中包含可以发布的不同types的博客。

我想在BlogDB中存储用户(谁发布了博客)的参考和博客的类别。 我所做的模式如下 –

博客架构 –

var blogSchema = new mongoose.Schema({ title: String, content: String, image: String, createdAt: Date, blogCategory : { id: { type : mongoose.Schema.Types.ObjectId, ref : "Category" } }, author: { id: { type: mongoose.Schema.Types.ObjectId, ref: "User" }, username: String }}); 

用户架构 –

 var UserSchema = new mongoose.Schema({ firstname: String, lastname: String, username: String, password: String, email: String }); 

类别Schema-

 var categorySchema = new mongoose.Schema({ name : String }); 

现在,当我在数据库中保存一个博客时,它会正确存储所有数据,除了“blogCategory”字段。 它甚至没有注册它。 甚至不用这个名字创build一个空字段。

是不是可以在一个模式中添加2个引用? 我能在这里做什么?

另外,我对NodeJS和MongoDB非常陌生。 这里的任何build议表示赞赏。 请告诉我如何能够实施这个想法,如果我应该采取一些不同的方法。 谢谢!

好吧,我花了一点时间来解决,首先为您的模式创build模型:

 For user: var usermodel = mongoose.model('User',UserSchema). Note: Pass reference for author as 'User' <first argument in mongoose.model()>. For blogCategory: var blogCategorymodel = mongoose.model('Category',cateogrySchema). Note: Pass reference for blogCategory as 'Category' <first argument in mongoose.model()>. Now we are left with only the saving stuff: To Save Them Create instances of each user and blogCategory models: var newuser = new usermodel({give the details}). var newcateogry = new blogCategorymodel({give the details}). Now create model for your blog: var blogmodel = mongoose.model('blog',blogSchema). Now Create instance of your blogmodel: var newblog = new blogmodel({give the other details,'author.id':newuser._id,'author.username':newuser.username,'blogCategory.id':newcategory._id}) Now Save All Three: Promise.all([newuser.save(),newcateogry.save(),newblog.save()]).then((result)=>{console.log(result)})