Estoy creando un esquema Mongoose para una tienda
Tengo dos esquemas de owner
y shop
. Estoy tratando de agregar datos en show con ref como propietario, pero no sé cómo hacerlo.
aquí está mi estructura de esquema
const mongoose = require("mongoose"); var shopSchema = Schema({ location : String, startDate : Date, endDate : Date }); var ownerSchema = Schema({ fname : String, lname : String, shopPlace : [{ type: Schema.Types.ObjectId, ref: 'Shop' }] }); var Shop = mongoose.model('Shop', shopSchema); var Owner = mongoose.model('Owner', ownerSchema);
así es como se ve mi esquema y estoy tratando de agregar detalles del propietario y la tienda, pero no sé cómo hacerlo si es un esquema único, puedo hacerlo fácilmente pero con ref no puedo
const Owner = require("../models/ownerSchema"); const addTask = async (req, res) => { let newOwmer = new Owner(req.body); try { newOwner = await newOwner.save(); cosnole.log("Added Successfully"); } catch (err) { console.log(err); } };
Puedo agregar fácilmente pero no sé cómo agregar una tienda
tendrias que hacer algo asi
const mongoose = require("mongoose"); var ownerSchema = Schema({ fname : String, lname : String, shopPlace : [{ type: Schema.Types.ObjectId, ref: 'Shop' }] }); var Owner = mongoose.model('Owner', ownerSchema); var shopSchema = Schema({ location : String, startDate : Date, endDate : Date, owner: Owner }); var Shop = mongoose.model('Shop', shopSchema);
Luego, cuando cree una tienda, primero cree un propietario y agregue el propietario en la creación de una tienda. tal vez así
// Import your shop and owner models const fetchedOwner = await Owner.get('the-owner-id') const createShop = { location : 'London' startDate : 'some date' endDate : 'another date' owner: fetchedOwner } await Shop.create(createShop)