2011-11-13 5 views
44

mongoHQ 및 mongoose에서 node.js, mongodb를 사용합니다. 카테고리에 대한 스키마를 설정하고 있습니다. 내 categoryId로 ObjectId 문서를 사용하고 싶습니다.몽구스에서 ObjectId를 데이터 형식으로 설정하는 방법

var mongoose = require('mongoose'); 

var Schema = mongoose.Schema, 
    ObjectId = Schema.ObjectId; 
var Schema_Category = new Schema({ 
    categoryId : ObjectId, 
    title  : String, 
    sortIndex : String 
}); 

나는 그때 카테고리 ID에 대한 값을 제공하지 않는

var Category = mongoose.model('Schema_Category'); 
var category = new Category(); 
category.title = "Bicycles"; 
category.sortIndex = "3"; 

category.save(function(err) { 
    if (err) { throw err; } 
    console.log('saved'); 
    mongoose.disconnect();  
}); 

공지 사항을 실행합니다. 나는 몽구스가 그것을 생성하기 위해 스키마를 사용할 것이라고 생각했지만, 문서는 "categoryId"가 아닌 일반적인 "_id"를 가지고있다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

답변

95

전통적인 RBDM과 달리 mongoDB는 모든 임의의 필드를 기본 키로 정의 할 수 없으며 _id 필드가 모든 표준 문서에 존재해야합니다.

이러한 이유 때문에 별도의 uuid 필드를 만드는 것이 의미가 없습니다.

mongoose에서 ObjectId 유형은 새로운 uuid를 작성하지 않고 주로 다른 문서를 참조하는 데 사용됩니다. 당신이 볼 수 있듯이

var mongoose = require('mongoose'); 

var Schema = mongoose.Schema, 
    ObjectId = Schema.ObjectId; 
var Schema_Product = new Schema({ 
    categoryId : ObjectId, // a product references a category _id with type ObjectId 
    title  : String, 
    price  : Number 
}); 

, 그것은 ObjectId가와 카테고리 ID를 채울 수 많은 이해가되지 것 : 여기

은 예입니다.

그러나 uuid라는 이름의 필드가 필요하다면 mongoose는 필드를 프록시 (참조) 할 수있는 가상 속성을 제공합니다.

를 체크 아웃 :

var mongoose = require('mongoose'); 

var Schema = mongoose.Schema, 
    ObjectId = Schema.ObjectId; 
var Schema_Category = new Schema({ 
    title  : String, 
    sortIndex : String 
}); 

Schema_Category.virtual('categoryId').get(function() { 
    return this._id; 
}); 

그래서 지금, 당신이 category.categoryId를 호출 할 때마다, 몽구스는 대신에 _id를 반환합니다.

당신은 가상 속성을 설정 추가 정보를 원하시면 this link 을 확인할 수 있도록 당신은 또한 "설정"방법을 만들 수 있습니다

+0

완벽한 답변! 감사합니다. – idophir

+0

가상 속성을 설정 한 후 시도 : db.cats.find ({categoryId : ObjectId ("id")})) 결과가 없습니다. 내가 db.cats.find를 사용할 때 ({_ id : ObjectId ("id")}) 나는 의사를 다시 얻었습니다. 따라서 가상 속성을 검색에 사용할 수없는 것처럼 보입니다. 모든 ID에 대해 _id를 사용하는 대신 명확한 이름을 사용하여 각 ID를 참조 할 수 있다면 코드 관리가 더 쉬울 것이라고 생각합니다. 그냥 생각 ... – idophir

12
나는 질문 제목에 다른 대답을 찾고 있었다

, 그래서 아마 다른 사람이 될 것입니다 너무. (당신은 예를 들어, book의 저자로 author를 참조 할 수 있도록)

당신이 할 수 ObjectId가로 유형을 설정하려면 :
// usermodel.js 

const mongoose = require('mongoose') 
const Schema = mongoose.Schema 
const ObjectId = Schema.Types.ObjectId 


let UserSchema = new Schema({ 
    username: { 
    type: String 
    }, 
    events: [{ 
    type: ObjectId, 
    ref: 'Event' // Reference to some EventSchema 
    }] 
}) 

UserSchema.set('autoIndex', true) 

module.exports = mongoose.model('User', UserSchema) 

을 ObjectId가

사용에

const Book = mongoose.model('Book', { 
    author: { 
    type: mongoose.Schema.Types.ObjectId, // here you set the author ID 
              // from the Author colection, 
              // so you can reference it 
    required: true 
    }, 
    title: { 
    type: String, 
    required: true 
    } 
}); 
+0

감사합니다 – Maverick

0

내 솔루션 몽구스의 populate 방법 사용

// controller.js 

const mongoose = require('mongoose') 
const User = require('./usermodel.js') 

let query = User.findOne({ name: "Person" }) 

query.exec((err, user) => { 
    if (err) { 
    console.log(err) 
    } 

    user.events = events 
    // user.events is now an array of events 
}) 
0

@dex에서 제공하는 솔루션이 나를 위해 일했습니다. 하지만 나를 위해 일한 다른 것을 추가하고 싶습니다 : 사용하고자하는 것이 Array 참조라면 Use

let UserSchema = new Schema({ 
    username: { 
    type: String 
    }, 
    events: [{ 
    type: ObjectId, 
    ref: 'Event' // Reference to some EventSchema 
    }] 
}) 

을 참조하십시오.당신이 원하는 것은 어쨌든 찾고 될 일을 내가 생각되는 객체 참조 인 경우에,이처럼 소품에서 브래킷을 제거합니다 아니라 2 개 조각에서

let UserSchema = new Schema({ 
    username: { 
    type: String 
    }, 
    events: { 
    type: ObjectId, 
    ref: 'Event' // Reference to some EventSchema 
    } 
}) 

봐. 두 번째 경우 키 이벤트의 값 prop에는 오브젝트 def에 대괄호가 없습니다.

관련 문제