Mongoose模型方法:属性不保存?

问题描述:

我试图写一个猫鼬模式,将基于对象我传中填充一些字段的方法Mongoose模型方法:属性不保存?

let mySchema = mongoose.Schema({ 
    name: String, 
    age: Number, 
    street: { type: String, default: 'No' } 
}); 

mySchema.methods.populate = function(o) { 
    this.age = o.age + 10; 
}); 

在其他地方,我会初始化实例和运行方法:

let newThing = new MySchema(); 
newThing.populate({ age: 12 }); 
newThing.save(); 

这样可以成功地在mongo中保存一个新的对象,并且没有默认街道名称以外的其他属性。难道我做错了什么?

+0

你正在导出你的模式?因为代码中没有其他错误。 – Khurram

+0

@Kururram如果他不会导出架构,他能保存甚至默认值吗? – Tolsee

你可以参考这个代码工作。

server.js

var mongoose = require('mongoose') 
    var Model = require('./model') 

    mongoose.Promise = global.Promise; 
    mongoose.connect('**dbUrl**') 

    var NewData = new Model({ 
     name: 'Tolsee' 
    }) 

    NewData.populate({ age: 15 }) 

    NewData.save(function(err){ 
     if (err) { 
      throw err 
     }else{ 
      console.log('Your data is saved successfully') 
     } 
    }) 

model.js

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

const customSchema = new Schema({ 
    name: String, 
    age: Number, 
    street: { type: String, default: 'No' } 
}) 

// Custom function 
customSchema.methods.populate = function(o) { 
    this.age = o.age 
    return this.age 
} 

// create the model to export 
var custom = mongoose.model('customModel', customSchema) 

module.exports = custom 

首先,你需要为了使用该模式以创建模型。这些模型的实例是可以使用您定义的自定义方法的文档。