猫鼬用包含 ref 的对象数组填充

我有一个 Mongoose 模式,它的对象数组 lists包含对另一个集合的引用和嵌套的数字数组:

var Schema, exports, mongoose, schema;
    

mongoose = require("mongoose");
    

Schema = mongoose.Schema;
    

schema = new Schema({
name: {
type: String,
required: true,
unique: true,
trim: true
},
lists: [{
list: {
type: Schema.ObjectId,
require: true,
ref: "List"
},
allocations: [{
type: Number,
required: true
}]
}],
createdAt: {
type: Date,
"default": Date.now
},
updatedAt: {
type: Date
}
});
    

exports = module.exports = mongoose.model("Portfolio", schema);

但是,如果没有 TypeError: Cannot read property 'ref' of undefined,我就无法让 populate按预期工作。我已经尝试了 populate('list')populate('lists list'),但是我要么没有正确地调用它们,要么我的 Schema 没有正确地形成。如果我只是简单地引用这些列表,我就不会有这个问题:

lists: [{
type: Schema.ObjectId,
require: true,
ref: "List"
}]

但我希望每个列表旁边都有分配数组。我需要做什么才能得到我想要的行为?

127991 次浏览

I found the answer: populate('lists.list') works. Thanks to this question: Mongoose populate within an object?

// Cart schema
var CartSchema = new mongooseSchema({
productDetails: [{
productId: {
type: mongoose.Schema.ObjectId,
required: true,
ref: 'Product'


},
productCount: Number,
}],
UserId: {
type: String,
default: '',
required: true,
trim: true,
},
shopId: {
type: String,
default: '',
required: true,
trim: true,
},
});


// add this .populate('productDetails.productId').


db.Cart.find({
UserId: userId,
shopId: shopId
}).populate('productDetails.productId')
.skip(pagination.skip)
.limit(pagination.limit)
.exec(function(error,


CartList) {


if (error) {
callback(error, null)
} else {
callback(null, CartList)
}
});
lists: [{
list: {
type: Schema.ObjectId,
require: true,
ref: "List"
},
allocations: [{
type: Number,
required: true
}]
}],

=> Because it's an array of objects, you can do this -: Portfolio.populate('lists.list');

2.

lists: [{
type: Schema.ObjectId,
require: true,
ref: "List"
}]

=> Because it's an array, you just have to do this -: Portfolio.populate('lists');

Actual answer:

Use this,

populate('lists.list')

Extra:

Here are lists are an array of objects (list). In JS you can access this like that,

console.log(lists.list);

and MongoDB syntax is 99% similar to JS syntax. so....................

Populate didn't work in my case when nesting to array my Schema was

const chatSchema = mongoose.Schema({
chats: [{
type: Schema.Types.ObjectId,
ref: "ChatMsg"
}],
})

How I solved it

Chat.findOne({
customer: req.body.customer,
agency: req.body.agency
}, (err, chat) => {
if (err) {
res.status(422).send("Our fault");
}


chat.populate("chats").execPopulate(() => {
res.send(chat);
});
});

if you have nested schema

YourSchema.find()
.populate({
path: 'map_data',
populate: {
path: 'location'
}
})

it's work for me