gpt4 book ai didi

node.js - 使用不是 id 的字段填充 mongoose 模型

转载 作者:IT老高 更新时间:2023-10-28 13:04:49 25 4
gpt4 key购买 nike

是否可以使用不是 _id 的引用模型字段填充 Mongoose 模型...例如用户名。

有点像

var personSchema = Schema({
_id : Number,
name : String,
age : Number,
stories : { type: String, field: "username", ref: 'Story' }
});

最佳答案

Mongoose 4.5 开始支持此功能,称为 virtuals population

您必须在架构定义之后和创建模型之前定义您的外键关系,如下所示:

// Schema definitions

BookSchema = new mongoose.Schema({
...,
title: String,
authorId: Number,
...
},
// schema options: Don't forget this option
// if you declare foreign keys for this schema afterwards.
{
toObject: {virtuals:true},
// use if your results might be retrieved as JSON
// see http://stackoverflow.com/q/13133911/488666
//toJSON: {virtuals:true}
});

PersonSchema = new mongoose.Schema({id: Number, ...});


// Foreign keys definitions

BookSchema.virtual('author', {
ref: 'Person',
localField: 'authorId',
foreignField: 'id',
justOne: true // for many-to-1 relationships
});


// Models creation

var Book = mongoose.model('Book', BookSchema);
var Person = mongoose.model('Person', PersonSchema);


// Querying

Book.find({...})
// if you use select() be sure to include the foreign key field !
.select({.... authorId ....})
// use the 'virtual population' name
.populate('author')
.exec(function(err, books) {...})

关于node.js - 使用不是 id 的字段填充 mongoose 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19287142/

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