sasuri
sasuri

Reputation: 992

How to save a refrence between 2 collections in MongoDB?

I'm developing an app using Node.js, Mongoose, MongoDb, express.

I have 2 schemas one for student and one for snippets. I'm using the population model population model. I can create a user, and create a snippet and link it to the user. But I can't link and save the snippets in the user collection.

How to link and save the user so that it can have a reference to his snippets?

user and snippet schema

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
}
})

This is how I save the user which usually when the user register.

 var username = request.body.name
var password = request.body.password
var newUser = new User({
  name: username,
  password: password
})
newUser.save().then(function () {
  console.log('success')

  response.redirect('/')
})

This is how I save the snippets I add it inside a user .save() function so that it saves the snippet ref but it gives me name.save() is not a function error.

var name = request.session.name.name

  name.save().then(function () {
       // Using a promise in this case
    var newSnippet = new Snippet({
      user: name._id,
      title: title,
      body: snippet
    })

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

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

    console.log(error.message)

    response.redirect('/')
  })

Upvotes: 0

Views: 46

Answers (1)

TGrif
TGrif

Reputation: 5941

name.save() is not a function because name is just a string in this case, not a Mongoose object.

One way to do it is to create your user, then retrieve it and add a snippet:

var name = request.session.name.name

User.find({ name: name }).then(function (user) {
  // Here you get your user by name
  var newSnippet = new Snippet({
    user: user._id,  // And here you can pass user _id
    title: 'your title',
    body: 'your snippet'
  })

  newSnippet.save()
})

Upvotes: 1

Related Questions