将猫鼬对象保存到两个集合中 [英] Saving Mongoose object into two collections

查看:86
本文介绍了将猫鼬对象保存到两个集合中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我有一个节点应用程序,该应用程序使用mongoose将对象保存到MongoDB中.我正在使用与此类似的模型:

Currently I have a node application which uses mongoose to save an object into a MongoDB. I am using a model similar to this:

var mongoose = require('mongoose')
    , Schema = mongoose.Schema;

var RegistrationSchema = new Schema({
        name:{ type: String, default: '', trim: false}
});

mongoose.model('Registration', RegistrationSchema);

将我的对象保存到称为注册的集合中.

Which saves my objects into a collection called registrations.

我将自己的注册保存为这样:

I save my registrations as such:

var registration = new Registration(data);

      registration.save(function(err) {
        if (err) {
          return callback({
            source: 'data_save',
            type: 'admin',
            errors: err
          });
        }
        else {
          return callback(null, data);
        }
      });

我还想在创建该对象时将其保存到另一个具有不同名称的集合中,例如registrations_new或类似的名称.我想将此条目复制到新集合中.我试图在连接字符串中添加其他集合,这完全打破了mongo的一部分,我试图创建一个名为New_Registration的新模型,加载该Schema并尝试单独保存它,但是与此有关的另一个问题.似乎Mongoose将架构与集合配对,并且确实没有办法覆盖将其保存到哪个集合.

I would also like to save this same object when I create it, into another collection with a different name, such as registrations_new, or something to that effect. I want to duplicate this entry into the new collection. I tried to add the other collection in the connection string, which broke the mongo part entirely, I tried to create a new model called New_Registration, load that Schema and try to save it individually, but I have another issue with that. It seems that Mongoose pairs the schema with the collection, and that there really is no way to overwrite which collection it is saving to.

有人对此有解决方案吗?

Anyone have any solution for this?

推荐答案

您可以在多个模型中使用相同的架构,因此可以使用以下方法:

You can use the same schema in multiple models, so something like this works:

var RegistrationSchema = new Schema({
    name:{ type: String, default: '', trim: false}
});

var Registration = mongoose.model('Registration', RegistrationSchema);
var New_Registration = mongoose.model('New_Registration', RegistrationSchema);

var registration = new Registration(data);
registration.save();

var new_registration = new New_Registration(data);
new_registration.save();

这篇关于将猫鼬对象保存到两个集合中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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