![](/img/trans.png)
[英]Is it possible to have mongoose populate a Mixed field only if the field contains an ObjectId?
[英]Mongoose populate a field without ObjectId?
我有一個架構:
var Schema = mongoose.Schema;
var TicketSchema = new Schema({
externalId: String,
name: String,
items: [{
externalId: String,
price: Number,
quantity: {
type: Number,
default: 1
},
comment: {
type: String,
default: '',
trim: true
},
entity: {
type: String,
ref: 'Entity'
}
}],
tableId: String
});
mongoose.model('Ticket', TicketSchema);
我想用 ObjectId 以外的唯一字段填充實體字段。 我怎樣才能做到這一點?
我不確定我是否正確理解了您的問題。
在Mongoose模型中,如果我們不指定主鍵,它將自動添加一個名為ObjectId的額外字段,並為每個對象分配一個唯一值。
如果需要指定自己的密鑰,可以通過指定key屬性來實現。
例如:
mongoose.model('Todo', {
todoID: {
type: String,
key: true
},
text: {
type: 'text'
},
done: {
type: Boolean,
default: false,
},
date: {
type: Date,
},
items: [{
entity: {
type: String,
ref: 'Entity'
}
}]
});
我希望這就是你的意思。
如果您要詢問是否要根據Items->實體的屬性獲取對象,
Todo.find({'items.entity.type':required_type}, function(err, foundTodos){
// ---
});
謝謝,
使用crypto來哈希諸如objectId之類的唯一事物,然后將其保存到您的實體中。
Var hash = crypto.createHmac('sha256', ticket.objectId).digest('hex');
Ticket.entities =哈希;
我發現視圖是一種有用的方法,盡管不確定它是否最有效! 例如,在movielens數據庫中,我想使用“ movieId”作為外鍵將收視率集合中的“ movieId”引用到電影集合中的“ movieId”。
db.createView('rating-movie-view','ratings',[{$lookup:{from:"movies",localField:"movieId",foreignField:"movieId",as:"ratings_movie"}},{ $project:{'userId':1,'movieId':1,'rating':1,'timestamp':1,'ratings_movie.title':1,'ratings_movie.genres':1 } }])
這樣創建的新視圖“ rating-movie-view”具有必填字段“ title”和“ genre”。
db["rating-movie-view"].findOne()
{
"_id" : ObjectId("598747c28198f78eef1de7a3"),
"userId" : 1,
"movieId" : 1129,
"rating" : 2,
"timestamp" : 1260759185,
"ratings_movie" : [
{
"title" : "Escape from New York (1981)",
"genres" : "Action|Adventure|Sci-Fi|Thriller"
}
]
}
希望這個有用!
那些不熟悉Movielens數據的人是模式
var MovieSchema = new mongoose.Schema({
movieId: Number,
title: String,
genres: String,
});
var RatingSchema = new mongoose.Schema({
userid: Number,
movieId:Number,
rating: Number,
timestamp:Number,
});
//查看架構
var RatingViewSchema = new mongoose.Schema({
userid: Number,
movieId:Number,
rating: Number,
timestamp:Number,
rating_movie:{title:String,genres:String}
});
雖然回答晚了。 請檢查填充虛擬貓鼬4.5.0
點擊下面的鏈接
http://mongoosejs.com/docs/populate.html
向下滾動或搜索“填充虛擬”,您將看到它完全符合您的要求。
const blogs = this.blogModel.find(find).populate('blogCategory', 'name -_id');
注意 -_id 將排除 object _id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.