gpt4 book ai didi

mongodb - 如何从 MongoDb 获取专业名称

转载 作者:搜寻专家 更新时间:2023-10-30 23:38:28 25 4
gpt4 key购买 nike

我在 mongoDB 中有这样的站点模式

const CitiesSchema =  new Schema({
name:{ type:String }
id:Object.id
});

并且有这样的用户模式

const UserSchema =  new Schema({
name: { type:String, default:'' },
surname: { type:String, default:'' },
foreName: { type:String, default:'' },
email: { type:String, default:'', unique:true },
password: { type:String, default:'' },
phone: { type:String, default:'' },
role: { type:String, default:'' },
profileImg: { type:String, default:'/images/profile.png' },
createdAt: { type:Date, default:Date.now },
city: { type: Schema.Types.ObjectId, ref: 'Story' }
}, { strict: false });

我怎样才能像这样与用户一起获得城市名称:

{
name:'xxxxx',
surname:'xxxxx',
city:'xxxxx' // not Object id, but name
......
}

非常感谢!!!!

最佳答案

您可以使用 Mongoose population将查询结果中的城市键替换为城市集合中的对象而不是引用。因此,如果您这样编写用户查询:

User
.findOne({ name: 'Jane' })
.populate('city')
.exec(function (err, user) {
if (err) return handleError(err);
console.log('The user lives in %s', user.city.name);
// prints "The user's lives in Amsterdam"
});

您将在 user.city.name 中获得城市名称。

关于mongodb - 如何从 MongoDb 获取专业名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38311140/

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