2016-12-14 4 views
1

node.js 애플리케이션을 개발하는 중입니다. 나는 이름과 관련된 사항을 가지고 있습니다 음계, 모델링하기 위해 노력하고있어 : 그러나Node.js + Mongoose의 기본 모델링

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

var scaleSchema = new Schema({ 
    name: String, 
    displayName: String, 
    notes: [{type: String}] 
}); 

module.exports = mongoose.model('Scale', scaleSchema); 

을,이 모델에 액세스 "씨"또는하는 방법을 모르겠어요. 한 번에로드되는 일부 비늘로 채우기를 원합니다. 나는이 모델을 요구할 수 있고 새로운 엔트리를 만들기 위해 new을 사용할 수 있다는 것을 알고 있지만 이것을 넣어야하는 노드 애플리케이션의 특정 부분이 있습니까? 어떤 모범 사례를 사용해야합니까? 내가 잘못 했니?

나는 여기에서 꽤 혼란 스럽다. 그러나 나는 그것이 어떻게 작동하는지 거의 이해하고있는 것처럼 느낀다. 누군가 올바른 방향으로 나를 가리킬 수 있습니까?

답변

2

개체를 만드는 것처럼 새 데이터베이스 항목을 만들 수 있습니다. 다음은 시드 클래스입니다.

let mongoose = require('mongoose'), 
    User = require('../models/User'); 

    module.exports =() => { 

    User.find({}).exec((err, users) => { 
     if (err) { 
      console.log(err); 
     } else { 
      if (users.length == 0) { 
       let adminUser = new User(); 
       adminUser.username = 'admin'; 
       adminUser.password = adminUser.encryptPassword('admin'); 
       adminUser.roles = ['Admin']; 
       adminUser.save(); 

       console.log('users collection seeded') 
      } 
     } 
    }); 
}; 

그런 다음 다른 파일에서이 파일을 호출하면 해당 파일이 시드됩니다.

let usersCollectionSeeder = require('./usersCollectionSeeder');  
usersCollectionSeeder(); 

희망이 있습니다.

구조의 경우 나는 "시더 (seeders)"라는 폴더를 갖고 싶어합니다. 거기에는 usersCollectionSeeder.js와 같은 다른 모든 시드를 필요로하는 databaseSeeder.js라는 파일이 있고 그 다음 함수를 호출합니다.

다음은 내가 사용하고자하는 샘플 구조입니다.

https://github.com/NikolayKolibarov/ExpressJS-Development

0

.create() a mongoose function을 살펴볼 수 있습니다. 이 그것을 할 수있는 유일한 방법 인 경우

는 잘 모르겠어요,하지만 당신은 다른 부분에서

Scale.create({name: varThatHasValName, 
      displayName: varThatHasValdisplayName, 
      notes: varThatHasValnotes}, function (err,scale)); 

같은 그런 당신이 할 수있는

var Scale = mongoose.model("Scale", scaleSchema); 
module.exports = Scale; //instead of what you currently have for you last line 

같은 것을 무언가를 추가 할 수 있습니다 새로운 스케일을 만들고 싶을 때 코드의

나는 최근에 노드와 몽구스를 수업에 사용했지만 전문가는 아니지만 아마도 (내가 당신의 질문을 이해한다면) 내가 할 수있는 일이다.