Answer the question
In order to leave comments, you need to log in
How to refer from one scheme to the second one?
There are two models (in two files): Brand.js
andProduct.js
const brandSchema = new mongoose.Schema ({
name: String,
image: String
})
const productSchema = new mongoose.Schema ({
name: String,
image: String,
brand: { тут обратится к brandSchema }
})
productSchema
even know which one brand.name
to contact? It turns out that I have to get either a list of all available brands in advance (like the GUI in the CMS admin panel), or in another way a sign to which document to refer to? For example, searching for just matches name
populate
n’t find anything at all, and I didn’t find the answer in the documentation.
Answer the question
In order to leave comments, you need to log in
const Schema = mongoose.Schema; //так просто удобнее
const brandSchema = new Schema ({
name: String,
image: String
});
const productSchema = new Schema ({
name: String,
image: String,
brand: { type: Schema.Types.ObjectId, ref: 'Brand' } // этот ref ссылается на имя модели, которое будет ниже
});
var Brand = mongoose.model('Brand', brandSchema); // вот оно, это имя в казычках
var Product = mongoose.model('Product', productSchema);
var briony = new Brand({
name: "Briony",
image: ".../briony.jpg"
});
var shapka = new Product({
name: "Shapka",
image: "...../shapka.jpg",
brand: briony // тут id брэнда этой шапки (как показал чувак в том ответе - и я проверял - mongoose сам сообразит именно id брэнда вписать по переменной briony, но можно и явно - briony._id)
});
briony.save();
shapka.save();
populate
. Its meaning is not to transfer to the document a lot of information about the document associated with it - when there is really a lot of this information. And there are only two lines: the name and a link to the logo. const brandSchema = new Schema ({
name: String,
image: String,
products: [{ type: Schema.Types.ObjectId, ref: 'Product' }]
});
var briony = new Brand({
name: "Briony",
image: ".../briony.jpg"
});
briony.products.push(shapka._id);
Product
.findOne({ name: 'Shapka' })
.populate('brand') // это означает "заселить", т.е. по айдишнику, вписанному в поле brand продукта, найти в коллекции брендов - нужный брэнд и вывалить сюда всю о нём информацию
.exec ... // и т.д.
Product
.findOne({ name: 'Shapka' })
.populate('brand', 'image')
.exec ... // и т.д.
.populate('brand', 'name')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question