MongoDb 中的集合引用并获取数据
Collections Referencing in MongoDb and fetching data
在 MongoDB 的集合中创建关系以通过 REST 获取数据时出现问题 API
我是 NodeJs 的新手,MongoDB,我正在尝试开发一个 REST API 来获取类别和产品的数据。我正在尝试创建关系 b/w 类别和产品,以便在查询特定类别时,只应从 DB
中获取这些产品
我试过从类别中获取数据,然后将 _id 传递到产品中以获取相关产品。
Categories.js 架构
const mongoose = require('mongoose')
const uniqueValidator = require('mongoose-unique-validator')
const categoriesSchema = mongoose.Schema({
name: {
type: String,
unique: true,
}
})
categoriesSchema.plugin(uniqueValidator)
module.exports = mongoose.model('Categories', categoriesSchema)
Prodcuts.js 架构
const mongoose = require('mongoose');
const ProductSchema = mongoose.Schema({
category:{
type: String
},
name:{
type: String,
required: true,
trim: true,
lowercase: true
} ,
description: {
type: String,
required: true,
trim: true,
lowercase: true
} ,
quantity: {
type: Number,
required: true,
trim: true,
default:0
} ,
color: {
type: String,
required: true,
trim: true,
lowercase: true
} ,
price: {
type: Number,
required: true,
trim: true,
default:0
}
});
module.exports = mongoose.model('Product', ProductSchema);
Home.js路线
const express = require('express')
const router = express.Router()
const productModel = require('../models/products')
const categoriesModel = require('../models/categories')
router.get('', async (req, res) => {
categroyFetched = []
productsFecthed =[]
await categoriesModel.find({})
.then(categories => {
categroyFetched = categories.map(category => {
return{
name: category.name,
id: category._id
}
})
return category = {
count: categroyFetched.length,
name: categroyFetched
}
})
.then(async()=>{
await productModel.find({category: categroyFetched.id})
.then(products => {
productsFecthed = products.map(product => {
return product
})
})
})
.catch(err => {
console.log('err', err)
})
res.status(200).json({
category, productsFecthed
})
})
module.exports = router
我需要帮助建立类别和产品架构中的关系,以及稍后如何在 Home.js 路由中使用它来提取数据。此外,在创建产品时,需要发送什么格式的 Json 数据以合并对类别集合的引用。
为了你的流量,
我们将从创建类别并将它们保存在数据库中开始,然后在创建产品时,我们将从数据库中获取所有类别并显示在 UI 中以供选择类别以创建产品。每个创建的产品在数据库中都有一个作为字符串的类别(如您在架构中所述)。
现在如果我们想要获取特定类别的产品,请尝试 productModel.find({category: specificCategory})
如果类别在产品中保存为字符串。这里的特定类别是您发送到服务器的内容。在您的查询中,如果您计划在产品中存储类别的 name
和 id
。然后,您必须在产品架构中将类别从字符串更改为对象。保存产品时,您应该将包含名称和 ID 的对象发送到产品。
如果您想同时获取所有类别以及每个类别的相关产品,请尝试 $lookup
mongodb 中的聚合查询。它们对于在单个查询中对多个集合执行操作非常有用。
为了在类别和产品之间建立关系,按如下方式定义您的产品架构:
const ProductSchema = mongoose.Schema({
category:{ type: mongoose.Types.ObjectId, ref: "Categories" },
// other fields...
现在为了在产品中插入记录,category 将使用 Category 的 ObjectId
(换句话说,Category 的 _id)。
现在可以查询,想干什么就干什么。
await Product.find().populate('category') // This will also populate category along with product
await Product.find({category: catId}).populate('category'); //conditional find statement
因为您正在使用类别 ID 建立关系。在产品架构中,将 categoryId 键从 string
更新为 mongoose.Types.ObjectId
。这在基于类别 id 关系执行聚合时很有用。现在创建类别和产品后,数据库中的文档将具有相同的键,可以用作相关文档之间的关系。
如果您选择 $lookup 来执行问题中的查询,那么在 Home.js
categoriesModel.aggregate([
{
$lookup:
{
from: "product",
localField: "_id",
foreignField: "categoryId",
as: "products"
}
}
])
预期结果将是所有类别的数组,其中产品作为每个元素的键。 products 是相应类别的产品数组
[{name:'category1', products:[{p1 Object},{p2 Object}, ...{}]}, {name:'category2', products:[{p6 Object},{p7 Object}, ...{}]}]
。试试这个。
在 MongoDB 的集合中创建关系以通过 REST 获取数据时出现问题 API
我是 NodeJs 的新手,MongoDB,我正在尝试开发一个 REST API 来获取类别和产品的数据。我正在尝试创建关系 b/w 类别和产品,以便在查询特定类别时,只应从 DB
中获取这些产品我试过从类别中获取数据,然后将 _id 传递到产品中以获取相关产品。
Categories.js 架构
const mongoose = require('mongoose')
const uniqueValidator = require('mongoose-unique-validator')
const categoriesSchema = mongoose.Schema({
name: {
type: String,
unique: true,
}
})
categoriesSchema.plugin(uniqueValidator)
module.exports = mongoose.model('Categories', categoriesSchema)
Prodcuts.js 架构
const mongoose = require('mongoose');
const ProductSchema = mongoose.Schema({
category:{
type: String
},
name:{
type: String,
required: true,
trim: true,
lowercase: true
} ,
description: {
type: String,
required: true,
trim: true,
lowercase: true
} ,
quantity: {
type: Number,
required: true,
trim: true,
default:0
} ,
color: {
type: String,
required: true,
trim: true,
lowercase: true
} ,
price: {
type: Number,
required: true,
trim: true,
default:0
}
});
module.exports = mongoose.model('Product', ProductSchema);
Home.js路线
const express = require('express')
const router = express.Router()
const productModel = require('../models/products')
const categoriesModel = require('../models/categories')
router.get('', async (req, res) => {
categroyFetched = []
productsFecthed =[]
await categoriesModel.find({})
.then(categories => {
categroyFetched = categories.map(category => {
return{
name: category.name,
id: category._id
}
})
return category = {
count: categroyFetched.length,
name: categroyFetched
}
})
.then(async()=>{
await productModel.find({category: categroyFetched.id})
.then(products => {
productsFecthed = products.map(product => {
return product
})
})
})
.catch(err => {
console.log('err', err)
})
res.status(200).json({
category, productsFecthed
})
})
module.exports = router
我需要帮助建立类别和产品架构中的关系,以及稍后如何在 Home.js 路由中使用它来提取数据。此外,在创建产品时,需要发送什么格式的 Json 数据以合并对类别集合的引用。
为了你的流量,
我们将从创建类别并将它们保存在数据库中开始,然后在创建产品时,我们将从数据库中获取所有类别并显示在 UI 中以供选择类别以创建产品。每个创建的产品在数据库中都有一个作为字符串的类别(如您在架构中所述)。
现在如果我们想要获取特定类别的产品,请尝试 productModel.find({category: specificCategory})
如果类别在产品中保存为字符串。这里的特定类别是您发送到服务器的内容。在您的查询中,如果您计划在产品中存储类别的 name
和 id
。然后,您必须在产品架构中将类别从字符串更改为对象。保存产品时,您应该将包含名称和 ID 的对象发送到产品。
如果您想同时获取所有类别以及每个类别的相关产品,请尝试 $lookup
mongodb 中的聚合查询。它们对于在单个查询中对多个集合执行操作非常有用。
为了在类别和产品之间建立关系,按如下方式定义您的产品架构:
const ProductSchema = mongoose.Schema({
category:{ type: mongoose.Types.ObjectId, ref: "Categories" },
// other fields...
现在为了在产品中插入记录,category 将使用 Category 的 ObjectId
(换句话说,Category 的 _id)。
现在可以查询,想干什么就干什么。
await Product.find().populate('category') // This will also populate category along with product
await Product.find({category: catId}).populate('category'); //conditional find statement
因为您正在使用类别 ID 建立关系。在产品架构中,将 categoryId 键从 string
更新为 mongoose.Types.ObjectId
。这在基于类别 id 关系执行聚合时很有用。现在创建类别和产品后,数据库中的文档将具有相同的键,可以用作相关文档之间的关系。
如果您选择 $lookup 来执行问题中的查询,那么在 Home.js
categoriesModel.aggregate([
{
$lookup:
{
from: "product",
localField: "_id",
foreignField: "categoryId",
as: "products"
}
}
])
预期结果将是所有类别的数组,其中产品作为每个元素的键。 products 是相应类别的产品数组
[{name:'category1', products:[{p1 Object},{p2 Object}, ...{}]}, {name:'category2', products:[{p6 Object},{p7 Object}, ...{}]}]
。试试这个。