我是猫鼬的新手,在其他地方找不到答案。
我有一个这样的用户架构:
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
},
admin: {
type: Boolean,
default: true
},
writer: {
type: Boolean,
default: true
},
producer: {
type: Boolean,
default: true
}
})
我想用他们的_id
来给某人起名字
我有这个:Users.findById(posts.userID).schema.obj.name
,但显然没有返回名字,谢谢!
答案 0 :(得分:1)
findById
返回a single document,其中包含您在架构中定义的属性的实际值。因此,如果您只是想从生成的文档中获取名称,可以执行以下操作:
const user = await Users.findById(posts.userID);
const name = user.name;
答案 1 :(得分:1)
通过猫鼬向mongo发送的任何请求都是异步的。 因此,.findById方法返回类似promise的对象。 您需要通过以下三种方式之一等待结果:
Users.findById(id, function (err, user) {
console.log(user.name);
});
Users.findById(id).then((user) => {
console.log(user.name);
});
async function getUser(id) {
const user = await Users.findById(id);
console.log(user.name);
};