gpt4 book ai didi

node.js - 如何向 MongoDB 中的单个模型添加 2 个引用?

转载 作者:太空宇宙 更新时间:2023-11-04 01:58:06 25 4
gpt4 key购买 nike

我正在开发一个博客网站(如 Medium),它将有一个用户模型、一个博客模型和一个类别模型。基本思想是将用户存储在Users DB中,Blogs DB中的所有博客和Category DB中包含可以发布的不同类型的博客。

我想在 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 });

类别架构-

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

现在,当我在数据库中保存博客时,它会正确存储除“blogCategory”字段之外的所有数据。它甚至没有注册它。甚至不创建具有该名称的空字段。

是否无法在单个架构中添加 2 个引用?我在这里能做什么?

另外,我对 NodeJS 和 MongoDB 非常陌生。如有任何建议,我们将不胜感激。请建议我如何实现这个想法,或者我是否应该采取一些不同的方法。谢谢!

最佳答案

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

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)})

关于node.js - 如何向 MongoDB 中的单个模型添加 2 个引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47104788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com