const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CompanySchema = new Schema(
{
companyName: {
type: String,
required: true,
unique: true
},
taxOffice: {
type: String
},
taxNumber: {
type: String
},
},
{
timestamps: true
}
);
const Company = mongoose.model('Company', CompanySchema);
module.exports = Company;
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const DateSchema = new Schema({
name: {
type: String,
unique: true,
required: true
},
companies: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Company' }]
});
const Date = mongoose.model('Date', DateSchema, 'dates');
module.exports = Date;
const router = require('express').Router();
const Date = require('../models/date');
router.route('/').get((req, res) => {
Date.find()
.then(dates => res.json(dates))
.catch(err => res.status(400).json('Error: ' + err));
});
router.route('/add').post((req, res) => {
const name = req.body.name;
const newDate = new Date({ name });
newDate
.save()
.then(() => res.json('Date added!'))
.catch(err => res.status(400).json('Error: ' + err));
});
module.exports = router;
{
name: "DECEMBER-2019",
companies: ['5e2076236664640d22515f7b', '5e2076236664640d22515f7a']
}
答案 0 :(得分:0)
听起来好像您想在Date集合中创建新文档时都采取措施。如果您使用Atlas(MongoDB的完全托管数据库即服务),则可以将触发器配置为在将新文档插入Date集合时触发。另一个选择(无论是否使用Atlas)都是使用Change Streams监视Date集合中的更改。有关如何配置它们的更多信息,请参见https://www.mongodb.com/blog/post/node-js-change-streams-and-triggers。
答案 1 :(得分:0)
假定仅应将在创建日期对象时存在的公司添加到“日期的公司”字段中,那么您可以在任何时间维护公司对象ID的缓存,该缓存将针对每个时间更新删除/插入公司集合中。
您可以编写自己的创建日期对象的功能,该日期对象的参数名称将添加当前公司的ObjectId。
Date.statics.getNewDateObject = function(name) {
let companyIds = await getCachedCompanyIds();
return new Date({name: name, companies: companyIds});
}
这将有一个文档,如:
{
name: "TODAY'S DATE",
companies: ['5e2076236664640d22515f7b', '5e2076236664640d22515f7a']
}
如果要用完整的公司信息填充Date对象,则可以使用猫鼬中出现的 populate 方法,该方法会将完整的公司信息填充到Date对象中。
答案 2 :(得分:0)
我解决了:
router.route('/add').post((req, res) => {
const name = req.body.name;
Company.find().then(companies => {
const newDate = new Date({ name, companies });
newDate
.save()
.then(() => res.json('Date added!'))
.catch(err => res.status(400).json('Error: ' + err));
});
});