Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了node.js – 继承Mongoose模式大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想创建一个基础’Entity scheR_754_11845@a’,其他模型实体将继承它.
我做到了,有点儿,但后来发生了奇怪的事情.

这些是我的模式:

> AbstractEntityscheR_754_11845@a
> messagescheR_754_11845@a
> UserscheR_754_11845@a
> RoomscheR_754_11845@a

档案:https://github.com/mihaelamj/nodechat/blob/master/models/db/mongo/schemas.js

但是在MongoDB中,它们都保存在同一个文档存储中:“实体模型”不是单独的,如消息,用户..
我得到了应该发生的事情,但不是我想要的,分开的商店?
如果是这样,我将只生成一个基本的JSON /对象作为实体,并为每个实体附加适当的属性.或者,还有更好的方法
谢谢.

解决方法

Discriminators是架构继承机制.它们使您能够在同一个基础MongoDB集合之上拥有多个具有重叠模式的模型.而不是不同的文件.你似乎误解了猫鼬的辨别者.这篇文章可以帮助您正确捕捉它.

Guide to mongoose discriminators

以下是一些符合您要求的代码示例,将派生架构保存为单独的文档

function AbstractEntityscheR_754_11845@a() {   
    //call super        
    scheR_754_11845@a.apply(this,arguments);     
    //add                                     
    this.add({                              
        entityName: {type: String,required: falsE},timestamp: {type: Date,default: Date.Now},index: {type: number,objectID: {type: String},id: {type: String}
    });                                     
};
util.inherits(AbstractEntityscheR_754_11845@a,scheR_754_11845@a);

//message scheR_754_11845@a
var messagescheR_754_11845@a = new AbstractEntityscheR_754_11845@a();
messagescheR_754_11845@a.add({
    text: {type: String,required: truE},author: {type: String,type: {type: String,required: falsE}
});

//Room scheR_754_11845@a
var RoomscheR_754_11845@a = new AbstractEntityscheR_754_11845@a();
RoomscheR_754_11845@a.add({
    name: {type: String,messages : [messagescheR_754_11845@a],});

var message = mongoose.model('message',messagescheR_754_11845@a);
var Room = mongoose.model('Room',RoomscheR_754_11845@a);

// save data to message and Room

var amessage = new message({
     entityName: 'message',text: 'Hello',author: 'mmj',type: 'article'
    });

 var aRoom = new Room({
     entityName: 'room',name: 'Room1',type: 'article'
 });

 aRoom.save(function(err,myRoom) { 
    if (err)
        console.log(err);
    else                                  
        console.log("room is saved"); 
 });

 amessage.save(function(err) {
    if (err)
        console.log(err);
    else
        console.log('user is saved');
 });

大佬总结

以上是大佬教程为你收集整理的node.js – 继承Mongoose模式全部内容,希望文章能够帮你解决node.js – 继承Mongoose模式所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。