将对象添加到嵌入式阵列

时间:2017-07-20 21:04:47

标签: node.js mongodb typescript mongoose

以下是我的架构,我将它们作为一个模型导出并导入我的路由器文件。

import { Schema, model } from 'mongoose';
//import  DateSchema from "./dateSchemaModel";

let DateSchemaModel : Schema = new Schema({
basicDate: String,
FY: String,
FQ: String,
CY: String,
CQ: String, 
PY: String,
PQ: String
})
let SupplierListSchema: Schema = new Schema({
name: 
{
type: String, 
required: true 
},
 price: 
{
type: Number,
required: true
},
dateObj: [DateSchemaModel]
});

export default model('SupplierList', SupplierListSchema);

然后我在路由器文件中导入此模型,如下所示。

 `import SupplierList from '../models/supplierListModel';`

然后我在typeScript中创建一个名为SupplierListRouter的类,该类具有REST调用的路由。

class SupplierListRouter 
{
router: Router;
constructor()
{
this.router = Router();
this.routes();
}



public AddDateObj(req: Request, res: Response, next: NextFunction): void {
const supplierId: string = req.params.supplierId;
//Create an instance of the model and assign it to the found document and then do 
//the save and other operations. 
var foundSupplierObj = new SupplierList();
const basicDate: string  = req.body.dateObj.basicDate;

//First find the specific supplier 
SupplierList.findById(req.params.supplierId, 
function(err,foundSupplierObj){
  if (err) throw err;
  foundSupplierObj.newNestedDateObj.push(req.body);
  foundSupplierObj.newNestedDateObj.save(function(err,supplierObj){
    if(err) throw err;
    console.log('Added a new dateObj');
    res.json(supplierObj);; 
  });

/* I tried this but this does not work.
  SupplierList.schema.methods.dateObj.push(req.body);
  SupplierList.schema.methods.dateObj.save(function(err,supplierObj){
    if(err) throw err;
    console.log('Added a new dateObj');
    res.json(supplierObj);
  });
  */
});
}

我正在尝试在dateObj数组中添加一个新文档。但我尝试使用推送,但这不起作用,也填充。我不知道如何在这里添加新文档作为嵌入式文档。有什么想解决这个问题的吗?

0 个答案:

没有答案