Marci81
7/18/2018 - 10:51 AM

Embeding data

var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/blog_demo3");

var postScheme = new mongoose.Schema({
    title: String,
    content: String
});

var userSchema = new mongoose.Schema({
    email: String,
    name: String,
    posts: [postScheme]
});

var User = mongoose.model("User", userSchema);


var Post = mongoose.model("Post", postScheme);


User.findOne({name: "Ben Johnson"}, function (err, user) {

    if (err) {
        console.log(err);
    } else {
      user.posts.push({
          title:"zzzzzzz",
          content: "Let's sleep"
      });
      user.save(function (err, user) {
          if (err) {
              console.log(err);
          } else {
              console.log(user);
          }
      })
    }
});