Wednesday, 3 May 2017

module.exports multiple mongoose.model

i wrote an embedded document in a mongoose schema according to the mongoose docs: http://mongoosejs.com/docs/2.7.x/docs/embedded-documents.html

this is the document child

var messages = new mongoose.Schema({
    User: { 
        _id: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
        email: {type : String, default: ''},
        name: {type : String, default: ''},
        username: {type : String, default: ''},
    },
    message: {type : String, default: ''},
    created: {type : String, default: behaviors.parseDate(Date())},
    updated: {type : String, default: behaviors.parseDate(Date())},
});

This is the parent document

var schema = new mongoose.Schema({
    Agent: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
    Customer: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
    Type: { type: mongoose.Schema.Types.ObjectId, ref: 'ConversationType' },
    active: { type: Boolean, default: false },
    order_id: {type : String, default: ''},
    establishment_id: {type : String, default: ''},
    messages: [messages],
    created: {type : String, default: Date()},
    updated: {type : String, default: Date()},

});

and in the end of the file i have

module.exports = mongoose.model('Conversation', schema);

what is the problem?

the problem is that i have a standalone model calles Message. i cant deleted cause it has an specific function, so tried to export the child schema to used but i seems like if not working.

i tried this according to this answer: cant get data from database after multiple schema declared (mongoose + express + mongodb

module.exports = {
    Conversation: mongoose.model(schema);,
    ConversationMessage: mongoose.model(message);
}

i need a new instance of the messagel model that is inside of ConversationModel (what i wrote) this is the way that i need to store mi documents:

var Conversation = require('../models/ConversationModel');
var Message = require('../models/MessageModel');
.
.
.

messages = new Message({
    User: {
        users
    },
    message: req.content,
    Conversation: conversations._id,
    User: users._id,
    unread: 1,
    image: image
});

conversations.updated = new Date();
conversations.messages.push(messages)
conversations.save();

free feel to ask whatever you need know to understand what i trying to do.



via Locojuhi

No comments:

Post a Comment