我在mongoDB中有这样的sities模式
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
......
}
非常感谢!!!!
答案 0 :(得分:1)
您可以使用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
中获取该城市的名称。