猫鼬与自定义字段的关系 [英] relations in mongoose with custom field

查看:60
本文介绍了猫鼬与自定义字段的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了很多有关猫鼬和关系的例子,但是如何在自定义字段中创建对另一个实体的引用?

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' }
}));

这篇关于猫鼬与自定义字段的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆