gpt4 book ai didi

node.js - Mongoose 填充在数组中

转载 作者:太空宇宙 更新时间:2023-11-03 23:02:05 24 4
gpt4 key购买 nike

我尝试玩 populate 但没有成功......可以这样做吗?

我有 2 个示玛:- 用户

import mongoose, { Schema } from 'mongoose'

const userSchema = new Schema({
email: { type: String, unique: true },
password: String,
passwordResetToken: String,
passwordResetExpires: Date,

products: [{
productId: { type: Schema.Types.ObjectId, ref: 'Product' },
dateAdd: { type: Date, default: Date.now }
}]
}, { timestamps: true })

const User = mongoose.model('User', userSchema)

export default User

和产品:

import mongoose, { Schema } from 'mongoose'

const productSchema = new Schema({
domain: String,
originUrl: { type: String },
price: Number,
img: String,
userFollow: [{ type: Schema.Types.ObjectId, ref: 'User' }]
})

const Product = mongoose.model('Product', productSchema)

export default Product

所以我想检索每个 prodcutId 的所有信息

我尝试这种方式(以及许多其他方式但没有成功):

User.findOne({ _id: userId }).populate({
path: 'products.productId',
populate: { path: 'products.productId', model: 'Products' }
}).exec(function (err, products) {
if (err) {
console.log('errors :' + err)
}
console.log('Product => ' + util.inspect(products))
})

填充没有效果,与 findOne() 的结果相同

最佳答案

我认为 User.findOne({ _id: userId }).populate('products.productId') 应该可以。

关于node.js - Mongoose 填充在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45168187/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com