Mongoose Virtuals in MongoDB Aggregate

后端 未结 3 1039
有刺的猬
有刺的猬 2021-01-12 08:12

My Mongoose Schema is as follows:

var DSchema = new mongoose.Schema({
  original_y: {type: Number},,
  new_y: {type: Number},,
  date: {type: Date},
  dummy         


        
相关标签:
3条回答
  • 2021-01-12 08:40

    A couple notes in the docs touch on why this is so:

    • Arguments are not cast to the model's schema because $project operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format.
    • The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).

    But it goes beyond this because the aggregate operation is performed server-side, where any client-side Mongoose concepts like virtuals do not exist.

    The result is that you'll need to include the date field in your $project and $group stages and add your own dateformatted field to the results in code based on the date values.

    0 讨论(0)
  • 2021-01-12 08:41

    the <field>: <1 or true> form is used to include an existing field which is not the case here since the dateformatted field doesn't exist and you have to create it using an expression, $dateToString can be used:

    "$project": {
      "original_y": 1, 
      "new_y": 1,
      "dateformatted": { "$dateToString": { "format": "%Y-%m-%d %H:%M:%S", "date": "$date" } },
      ...
    

    Another option is to use it with $addFields:

    {
      "$project": {
        ...
      }
    },
    {
      "$addFields": {
        "dateformatted": { "$dateToString": {"format": "%Y-%m-%d %H:%M:%S", "date": "$date"} }
      }
    },
    ...
    
    0 讨论(0)
  • 2021-01-12 08:49

    This is an old question but I've come up with a useful hack to get back the virtuals and thought it might be useful for those searching for this problem.

    You can easily convert the objects back to mongoose models:

    documents = documents.map(d => {
      return new Document(d);
    });
    
    var virtual = documents[0].virtualProperty;
    
    0 讨论(0)
提交回复
热议问题