node.js - 如何避免使用 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
解决方案
您必须在模型中定义这些属性。
/* 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;
推荐阅读
- python - SymPy 中更难的方程(带导数和积分)和条件集
- linux - Celery systemd 正确配置两个应用程序使用相同的守护程序服务
- laravel - 如何验证输入以仅接受 laravel 中的一个单词
- javascript - 如何阻止 location.href 在缩小的 javascript 上执行
- c - C中字符串中的子字符串替换
- css - 我如何在 laravel 的底部页面显示页脚?
- pandas - Pandas:创建随机样本和相关矩阵
- sql - 在 sqlldr 中加载数据需要时间
- sql - INSERT INTO @Temp_Table VALUES 从多值 SSRS 参数
- c# - 有什么方法可以检查套接字连接是否可用?