首页 > 解决方案 > 如何在猫鼬的另一个方案中添加参考和数据

问题描述

我正在为商店构建 Mongoose 模式

我有两个架构ownershop我正在尝试以 ref 作为所有者在 show 中添加数据,但不知道该怎么做

这是我的架构结构

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

所以这就是我的架构的样子,我正在尝试添加所有者和商店的详细信息,但如果它是单一架构我不知道该怎么做我可以轻松地做到这一点,但使用参考我不能

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

我可以轻松添加但不知道如何添加商店

标签: javascriptnode.jsmongodbmongoose

解决方案


你必须做这样的事情

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

然后在创建店铺的时候,先创建一个店主,在创建店铺的时候添加店主。也许像这样

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

推荐阅读