首页 > 解决方案 > 如何避免使用 mongoose 在 mongodb 中插入空记录

问题描述

在我的脚本中,我可以在 mongodb 中创建一个新集合,但默认插入一个空记录,因此如何避免这种情况。

模型.js:

 /* model.js */
 'use strict';

 var mongoose = require('mongoose'),
 Schema = mongoose.Schema;


 function dynamicModel(suffix) {
   var addressSchema = new Schema({

    product_name: {
        type: String
    }

   }); 
   return mongoose.model(suffix, addressSchema); 
  } 
  module.exports = dynamicModel;

data.controller.js:

      var NewModel = require(path.resolve('./models/model.js'))(collectionName);
      NewModel.create({ category: 1, title: 'Minion' }, function(err, doc) {

      });

创建新集合后,我看到的是这样的:

  _id:ObjectId("5eceb362d538901accc0fefe");
  __v:0

标签: node.jsmongodbmongoosemongodb-query

解决方案


您必须在模型中定义这些属性。

 /* model.js */
 'use strict';

 var mongoose = require('mongoose'),
 Schema = mongoose.Schema;


 function dynamicModel(suffix) {
   var addressSchema = new Schema({

    product_name: {
        type: String,
    },
    category: {
       type: Number,
    },
    title: {
       type: String,
    }

   }); 
   return mongoose.model(suffix, addressSchema); 
  } 
  module.exports = dynamicModel;

推荐阅读