C
C
CartmanGui2016-02-14 01:54:14
Node.js
CartmanGui, 2016-02-14 01:54:14

How to get data from an array field in mongoose?

There is the following model structure:

var Schema = mongoose.Schema;
var schemaMessage = new Schema({
    message: {
        type: String,
        required: true
    },
    from: {
        type: Schema.ObjectId
    },
    to: {
        type: Schema.ObjectId,
    },
    date_created: {
        type: Date,
        default: Date.now
    }
});

var schemaTopic = new Schema({
    title: {
        type: String,
        required: true
    },
    creator: {
        type: Schema.ObjectId,
        required: true,
        ref: 'User'
    },
    messages: [schemaMessage],
    date_created: {
        type: Date,
        default: Date.now
    }
});

I need to get n documents for a topic, I try to do it like this
schemaTopic.statics.getMessageList = function (topic,  callback) {
    console.log(topic);
    this.aggregate([
        {$match: {_id: topic}},
        {$unwind: "$messages"}
    ],callback);
};

but I get an empty array, but if in $match do a search not by _id, but for example by creator, then the document is located

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
CartmanGui, 2016-02-14
@CartmanGui

In general, as it turned out, it was necessary to convert topic to ObjectID
{$match: {_id: mongoose.mongo.ObjectID(topic)}}

V
vadimstroganov, 2014-10-23
@vadimstroganov

Changed .htaccess at the root to:

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_URI} !^public
    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

Now everything works.

S
Stanislav Kim, 2014-10-23
@cyberS7

Route::get('/en', '[email protected]_en');
// Должно быть так
Route::get('en', '[email protected]_en');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question