2017-12-11 12 views
0

私はNode.js、Mongoose、MongoDb、expressを使ってアプリを開発しています。mongooseのsave()がなぜ関数ではありませんか?

私は学生用とスニペット用の2つのスキーマを持っています。私は母集団モデル集団モデルを使用しています。ユーザーを作成し、スニペットを作成してユーザーにリンクすることができます。しかし、私はユーザーコレクションのスニペットをリンクして保存することはできません。

スニペットへの参照を持つようにユーザーをリンクして保存するにはどうすればよいですか? ()され

ユーザーとスニペットスキーマは

var userSchema = Schema({ 
     name: { type: String, required: true, unique: true }, 
    password: { type: String, required: true }, 
    snippet: [{ type: Schema.Types.ObjectId, ref: 'Snippet' }] 
    }) 

    var snippetSchema = Schema({ 
    user: {type: Schema.Types.ObjectId, ref: 'User'}, 
    title: String, 
    body: String, 
    createdAt: { 
    type: Date, 
    require: true, 
    default: Date.now 
    } 
    }) 

これは、スニペットの参照が保存されますように、私は、ユーザー.SAVE()関数の中にそれを追加しスニペットを保存する方法ですが、それは私をuser.saveいます機能エラーではありません。

var name = request.session.name.name 
    User.find({ name: name }).then(function (user) { 
    if (user) { 
     console.log('====================') 
     console.log(user) 
     user.save().then(function() { // problem is here? 
     var newSnippet = new Snippet({ 
      user: user._id, 
      title: title, 
      body: snippet 
     }) 

     newSnippet.save().then(function() { 
      // Successful 
      console.log('success') 

      response.redirect('/') 
     }) 
     }) 
    } 
    }).catch(function (error) { 
    console.log(error.message) 
    response.redirect('/') 
    }) 

しかし、私は実際にそれを検索した後にオブジェクトを印刷します!

[ { _id: 5a2e60cf290a976333b19114, 
name: 's', 
password: '$2a$10$vD3EaQly4Sj5W3d42GcWeODuFhmHCSjfAJ1YTRMiYAcDBuMnPLfp6', 
__v: 0, 
snippets: [] } ] 
+0

を避け、あなたが見ている正確なエラーメッセージとは何ですか? –

+0

user.save()は関数ではありません。 – sasuri

答えて

2

有効なユーザーオブジェクトを取得するには、User.findOneを使用する必要があります。ここでは配列が得られます。また、常に約束を返すことを忘れないでください(またはエラーを投げる)。

ここでは、機能の簡単な書き換えです。 (別の.then内の任意の.thenを使用したことがない)、このような矢印機能、constのフラット約束チェーンなど、いくつかの改良で、コードの繰り返しに

const name = request.session.name.name 
User.findOne({ name }) 
    .then(user => { 
    if (user) return user.save() 

    // What to do if not found? Throw an error? 
    throw new Error('User not found') 
    }) 
    .then(() => { 
    const newSnippet = new Snippet({ 
     user: user._id, 
     title: title, 
     body: snippet, 
    }) 

    return newSnippet.save() 
    }) 
    .catch((error) => console.log(error.message)) 
    .then(() => response.redirect('/')) 
関連する問題