首页 > 解决方案 > Mongoose Model.Create 和 Model.Update 另一个

问题描述

所以,我试图让两个模式之间的引用工作。当然,我可以毫无问题地创建两个模式,并且我可以对它们中的任何一个执行单个操作,但是我希望扩展它并创建一个模型,然后更新到另一个 $push 生成的新模型_id 给它。

const mongoose = require("mongoose"), Schema = mongoose.Schema;

const jobSchema = new Schema({
    _id: Schema.Types.ObjectId,
    fromBarcode: String, // AAA000+
    businessName: String,
    businessAddress: String,
    contactName: String,
    contactPhoneNumber: String,
    contactEmailAddress: String,
    notes: String,
    wipeReq: String,
    displayReq: String,
    collectionDate: Date,
    collectionTime: String,
    autoList: [{
        type: Schema.Types.ObjectId,
        ref: 'Auto'
    }],
    wipeList: [{
        type: Schema.Types.ObjectId,
        ref: 'Wipe'
    }],
    creation: {
        type: Date,
        default: Date.now()
    }
});

module.exports = mongoose.model('Job', jobSchema);

这就是工作模式。

const mongoose = require("mongoose"), Schema = mongoose.Schema;

const autoSchema = new Schema({
    _id: Schema.Types.ObjectId,
    fromId: {
        type: Schema.Types.ObjectId,
        ref: 'Job'
    },
    fromBarcode: String, //AAA000+
    locationBarcode: String, //AAA000+ future ref
    idBarcode: String, //AAA000+
    brand: String,
    product: String,
    version: String,
    serial: String,
    processor: String,
    ramTotal: String,
    hardDrive: String,
    notes: String,
    created: {
        type: Date,
        default: Date.now()
    }
});

module.exports = mongoose.model('Auto', autoSchema);

这是自动模式。

const express = require('express');
const router = express.Router;
const Auto = require('../model/Auto.js');
const Job = require('../model/Job.js');

router.get('/', function(req, res, next) {
    Auto.find().exec(jsonResponse);
    function jsonResponse(err, many) {
        if (err) return next(err);
        res.json(many);
    }
});

router.get('/:id', function(req, res, next) {
    Auto.findById(req.params.id, function(err, one) {
        if (err) return next(err);
        res.json(one);
    });
});

router.get('/id/:idBarcode', function(req, res, next) {
    Auto.findOne({idBarcode: req.params.idBarcode}, function(err, one) {
        if (err) return next(err);
        res.json(one);
    });
});

router.post('/', function(req, res, next){
    Auto.create(req.body).then(function(err, post) {
        if (err) return next(err);
        res.json(post);
    });
});

因此,在我的 Auto API 中,我在底部有一个 create 方法,如您所见,我还需要更新 Job 模式模型以将 ObjectID 添加到组合中。如果你想知道,我正在构建一个用于测试和擦除设备的 IT 资产管理软件。我使用在其上运行 OpenWRT 和 Node.js 的便携式设备与 MongoDB atlas 云存在进行交互。

标签: javascriptnode.jsmongodbmongoosemongoose-schema

解决方案


推荐阅读