我有一個名為“list”的模型,我必須在其中放入幾個專案。但是我制作了一個只能在串列中放入一個專案的代碼。誰能幫我解決這個問題?
我的型號:
const mongoose = require('mongoose');
const { itemSchema } = require('./item.js');
const { shopSchema } = require('./shop.js');
const listSchema = mongoose.Schema({
name: { type: String, required: true },
created: { type: Date, required: true, unique: true },
updated: { type: Date },
items: [itemSchema],
shop: [shopSchema]
});
module.exports.ListData = mongoose.model("listData", listSchema);
module.exports.listSchema = listSchema;
專案架構:
const mongoose = require('mongoose');
const categSchema = require("./category.js")
const itemSchema = mongoose.Schema({
name: { type: String, required: true },
created: { type: Date, required: true, unique: true },
category: [categSchema.categorySchema],
quantity: { type: Number, required: true }
});
module.exports.ItemData = mongoose.model("itemData", itemSchema);
module.exports.itemSchema = itemSchema;
我如何制作“物品:”來接收多個物品,而不僅僅是一個?我在這個專案中使用 mongodb。謝謝!
uj5u.com熱心網友回復:
您items已經接受了多個專案。這不是你想要的嗎?我用這個小實驗進行了測驗:
import connect from './db.js';
import mongoose from 'mongoose';
// this just connects to mongodb
await connect();
const itemSchema = mongoose.Schema({
name: { type: String, required: true }
});
const ItemData = mongoose.model("itemData", itemSchema);
const listSchema = mongoose.Schema({
name: { type: String, required: true },
items: [itemSchema]
});
const ListData = mongoose.model("listData", listSchema);
await ListData.deleteMany({});
// create items
await ItemData.create({ name: "potato" });
await ItemData.create({ name: "tomato" });
await ItemData.create({ name: "kitten" });
const items = await ItemData.find({});
await ItemData.deleteMany({});
// create list
await ListData.create({
name: "Stuff i luv",
items
});
// get inserted lists
const q = ListData.find();
q.select("-__v -_id -items.__v -items._id");
const ld = await q.exec();
// print results
console.log(JSON.stringify(ld));
// result is
[{
"name":"Stuff i luv",
"items":[{"name":"potato"},{"name":"tomato"},{"name":"kitten"}]
}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/343595.html
標籤:javascript 节点.js MongoDB 猫鼬
上一篇:NextJS/mongoose:在保存新物件之前將ObjectId分配到陣列中
下一篇:無法使用聚合填充和構建檔案
