作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我在 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/
我是一名优秀的程序员,十分优秀!