猫鼬不保存带有引用的架构到另一个集合

时间:2018-12-13 16:54:33

标签: javascript mongodb express mongoose

我在播种数据时遇到麻烦。我可以为Chapters植入种子,而Chapter有很多用户。我有一个单独的userSeed文件:

const faker = require("faker");
const bcrypt = require("bcryptjs");
const uuidv1 = require("uuid/v1");
// Bring in User model
const User = require("../models/User");
const Chapter = require("../models/Chapter");

// Bring in Mongoose and connect to DB
const mongoose = require("mongoose");
mongoose.Promise = require("bluebird");
const env = require("../config/keys");
mongoose.connect(
  env.db,
  {
    useNewUrlParser: true
  }
);
// Drop the collection to avoid duplicates
User.collection.drop();

// ========= INIT =========
function init() {
  Chapter.find()
    .then(chapters => {
      console.log(`${chapters.length} chapters `);
      chapters.forEach(chapter => {
        for (var i = 0; i < 10; i++) {
          const rand = Math.floor(Math.random() * 3000);
          let email = "";
          let password = "password";
          let admin = false;
          let lead = false;

          if (i === 0) {
            email = `admin${rand}@test.com`;
            admin = true;
          } else if (i === 1 || i === 2) {
            email = `lead${rand}@test.com`;
            lead = true;
          } else {
            email = `test${rand}@test.com`;
            admin = false;
          }
          const user = new User({
            username: faker.lorem.word(),
            firstName: faker.name.firstName(),
            lastName: faker.name.lastName(),
            organisation: faker.company.companyName(),
            chapter: chapter._id,
            email: email,
            password: password,
            admin: admin,
            lead: lead
          });

          bcrypt.genSalt(10, (err, salt) => {
            bcrypt.hash(user.password, salt, (err, hash) => {
              if (err) throw err;
              user.password = hash;
              console.log(user); // Successfully generates a user with hashed password
              // User.create(user, (err, user) => {
              //   // ATTEMPT 1 : no success.
              //   if (err) {
              //     console.log(err);
              //   } else {
              //     console.log(user);
              //   }
              // });
              user.save((err, user) => {
                // ATTEMPT 2 : no success.
                if (err) {
                  console.log(err);
                } else {
                  console.log(user);
                }
              });
            });
          });
        }
      });
    })
    .catch(err => console.log(err))
    .finally(() => mongoose.connection.close());
}

init();

如果您查看我的代码,您会发现我尝试了几种不同的方法来保存用户,但都无法正常工作。 console.log(user)下的user.password = hash可以正常工作(返回真正的Chapter._id和哈希密码),但是它无法保存。我(显然)是NoSQL和Mongoose的新手,来自关系数据库。下面是我的userModel

const UserSchema = new Schema({
  ...
  chapter: {
    type: Schema.Types.ObjectId,
    ref: "chapters"
  },
  ...
});

请注意,是否有人拥有学习异步javascript的良好资源?那里有很多东西,但是一些可靠的建议会很棒。谢谢!

0 个答案:

没有答案