Javascript 将默认值设置为节点js中的mongoose数组
在我的模型定义中,我有:Javascript 将默认值设置为节点js中的mongoose数组,javascript,node.js,mongodb,mongoose,mongodb-query,Javascript,Node.js,Mongodb,Mongoose,Mongodb Query,在我的模型定义中,我有: appFeatures: [{ name: String, param : [{ name : String, value : String }] }] 我想将默认值设置为appFeatures,例如: 名称:“功能”, param:[{name:'param1',value:'1'},{name:'param2',value:'2'}] 我试着用手做这件事 app
appFeatures: [{
name: String,
param : [{
name : String,
value : String
}]
}]
我想将默认值设置为appFeatures,例如:
名称:“功能”,
param:[{name:'param1',value:'1'},{name:'param2',value:'2'}]
我试着用手做这件事
appFeatures : { type : Array , "default" : ... }
但它不起作用,有什么想法吗
感谢Mongoose允许您“分离”模式定义。既可用于一般的“重用”,也可用于代码的清晰性。因此,更好的方法是:
// general imports
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
// schema for params
var paramSchema = new Schema({
"name": { "type": String, "default": "something" },
"value": { "type": String, "default": "something" }
});
// schema for features
var featureSchema = new Schema({
"name": { "type": String, "default": "something" }
"params": [paramSchema]
});
var appSchema = new Schema({
"appFeatures": [featureSchema]
});
// Export something - or whatever you like
module.export.App = mongoose.model( "App", appSchema );
因此,如果您愿意将“模式”定义作为单个模块的一部分,并根据需要使用“require”系统进行导入,那么它是“干净的”和“可重用的”。如果不想“模块化”所有内容,甚至可以从“模型”对象“内省”模式定义
不过,它主要允许您为默认设置明确指定“您想要什么”
对于更复杂的默认设置,您可能希望改为在“预保存”挂钩中执行此操作。作为更完整的示例:
var async = require('async'),
mongoose = require('mongoose'),
Schema = mongoose.Schema;
var paramSchema = new Schema({
"name": { "type": String, "default": "something" },
"value": { "type": String, "default": "something" }
});
var featureSchema = new Schema({
"name": { "type": String, "default": "something" },
"params": [paramSchema]
});
var appSchema = new Schema({
"appFeatures": [featureSchema]
});
appSchema.pre("save",function(next) {
if ( !this.appFeatures || this.appFeatures.length == 0 ) {
this.appFeatures = [];
this.appFeatures.push({
"name": "something",
"params": []
})
}
this.appFeatures.forEach(function(feature) {
if ( !feature.params || feature.params.length == 0 ) {
feature.params = [];
feature.params.push(
{ "name": "a", "value": "A" },
{ "name": "b", "value": "B" }
);
}
});
next();
});
var App = mongoose.model( 'App', appSchema );
mongoose.connect('mongodb://localhost/test');
async.series(
[
function(callback) {
App.remove({},function(err,res) {
if (err) throw err;
callback(err,res);
});
},
function(callback) {
var app = new App();
app.save(function(err,doc) {
if (err) throw err;
console.log(
JSON.stringify( doc, undefined, 4 )
);
callback()
});
},
function(callback) {
App.find({},function(err,docs) {
if (err) throw err;
console.log(
JSON.stringify( docs, undefined, 4 )
);
callback();
});
}
],
function(err) {
if (err) throw err;
console.log("done");
mongoose.disconnect();
}
);
您可以清理这些内容并内省模式路径,以获得其他级别的默认值。但是您基本上想说,如果没有定义内部数组,那么您将按照编码填写默认值。谢谢,您能解释一下如何添加两个featureSchema吗?比如我的例子?再次感谢@塔列维:当然。添加了一个添加两个内部项的更完整示例。