猫鼬与自定义字段的关系
问题描述:
我已经看到了很多有关猫鼬和关系的例子,但是如何在自定义字段中创建对另一个实体的引用?
I've seen many examples about mongoose and relations, but how can I create a reference to another entity into a custom field ?
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
mongoose.connection.once('open', function(){
var Author = m.model('Author', new m.Schema({
name: String,
slugname: String
}));
var Book = m.model('Book', new m.Schema({
title: String,
author: {type: String, ref: 'Author.slugname'}
}));
});
在上面的代码中,我将Book.author链接到Author.slugname中.只是我不知道这是否是正确的方法.
In the code above, I'm linking Book.author into Author.slugname. it is just that I don't if this is the right way to do it.
答
不,您不能.猫鼬总是使用_id
字段链接文档.但是...
No, you can't. Mongoose always use _id
field to link documents. But...
您可以使用所需的任何数据类型为每个文档设置自己的_id
.只有两个限制:
You can set your own _id
for each document, using any datatype you want. There are only two restrictions:
- 它应该是唯一的
- 在文档的生命周期内不得更改
因此,不要添加新的slugname
字段,而使用作者的_id
作为别名:
So, instead of adding new slugname
field, use author's _id
as a slugname:
var Author = m.model('Author', new m.Schema({
_id: String, // <-- slugname
name: String
}));
var Book = m.model('Book', new m.Schema({
title: String,
author: { type: String, ref: 'Author' }
}));