猫鼬:findOne返回的ObjectId未定义

时间:2020-08-03 06:13:04

标签: javascript mongoose

我正在尝试保存引用艺术家文档的书籍文档。但是,我无法从艺术家文档中获取objectId。当我尝试从艺术家文档中获取_id时,我将返回undefined。但是,如果我记录了整个演出者文档,则可以看到_id作为_id: ObjectID { _bsontype: 'ObjectID', id: [Buffer [Uint8Array]] }属于文档的一部分。

如何从艺术家文档中获取ObjectId并保存书籍文档,以便它引用艺术家文档?

const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;

var artistSchema = new Schema({
    name: { type: String, required: true },
    description: { type: String, default: null },
});
const Artist = mongoose.model('Artist', artistSchema);

var bookSchema = new Schema({
    name: { type: String, required: true },
    artist: { type: ObjectId, ref: 'Artist' },
});
const Book = mongoose.model('Book', bookSchema);

// ...

let artistId = await Artist.findOne({ name: 'John Smith'})._id;
console.log(artistId); // prints: undefined

let book = new Book({
    name: 'Book Name',
    artist: artistId,
});

1 个答案:

答案 0 :(得分:0)

您必须等待异步调用,而不是对_id的访问。更改

let artistId = await Artist.findOne({ name: 'John Smith'})._id;

let artistId = (await Artist.findOne({ name: 'John Smith'}))._id;

它应该可以工作。

例如:

function getId() {
    return new Promise((resolve) => {
        setTimeout(() => resolve({_id: 1}), 1000);
    });
}

async function run() {
    let id = await getId()._id;
    console.log(id);
    let id2 = (await getId())._id;
    console.log(id2);
}

run();