2016-05-21 4 views
7

私はUserエンティティ用のMongooseデータベーススキーマを作成し、現在の日付をupdated_atフィールドに追加したいとします。 .pre('save', function() {})コールバックを使用しようとしていますが、実行する度にエラーメッセージが表示されます。thisは定義されていません。私もES6を使用することに決めました。私はこれが理由だと思います。私のマングースは/ノードES6コードは以下の通りです:'this'はMongooseの事前セーブフックでは定義されていません

import mongoose from 'mongoose' 

mongoose.connect("mongodb://localhost:27017/database", (err, res) => { 
    if (err) { 
    console.log("ERROR: " + err) 
    } else { 
    console.log("Connected to Mongo successfuly") 
    } 
}) 

const userSchema = new mongoose.Schema({ 
    "email": { type: String, required: true, unique: true, trim: true }, 
    "username": { type: String, required: true, unique: true }, 
    "name": { 
    "first": String, 
    "last": String 
    }, 
    "password": { type: String, required: true }, 
    "created_at": { type: Date, default: Date.now }, 
    "updated_at": Date 
}) 

userSchema.pre("save", (next) => { 
    const currentDate = new Date 
    this.updated_at = currentDate.now 
    next() 
}) 

const user = mongoose.model("users", userSchema) 
export default user 

エラーメッセージは次のとおりです。

undefined.updated_at = currentDate.now; 
        ^
TypeError: Cannot set property 'updated_at' of undefined 

EDIT:vbrandenの答え@使用し、標準機能にレキシカル関数からそれを変更することにより、これを修正しました。しかし、私はその後、それがエラーを表示していない間に、オブジェクト内のupdated_atフィールドを更新していないという問題がありました。 this.updated_at = currentDate.nowthis.updated_at = currentDateに変更してこの問題を修正しました。関数宣言/表現VS [アロー機能:

+0

からhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

変更

userSchema.pre("save", (next) => { const currentDate = new Date this.updated_at = currentDate.now next() }) 

を字句使用している彼らは、交換/同等か? ](http://stackoverflow.com/q/34361379/218196) –

答えて

28

問題は、あなたの矢印機能は、この関連

userSchema.pre("save", function (next) { 
    const currentDate = new Date 
    this.updated_at = currentDate.now 
    next() 
}) 
+0

ありがとう!これでエラーは発生しなくなりましたが、新しいユーザーを作成するときにルートファイルに出力されるJSONオブジェクトに実際に 'updated_at'フィールドを追加することはありません。 'console.log(this.updated_at)'を実行すると 'undefined'が出力されます。なぜこれがあるのか​​知っていますか? –

+0

新しい日付の代わりに新しい日付()を使用してください。 – vbranden

+0

Thnx a lot !!これはちょっと時間を節約しました – Deadfish