1

我有以下架构:

var StorySchema = new Schema({
  title:        { type: String, required: true },
  users:        { 
                  id:        { type: Schema.ObjectId, ref: 'Users' },
                  creator:   { type: Boolean } 
                },       
  maxlines:     { type: Number, default: '10'},
  lines:        {
                  text:       { type: String },
                  entered_at: { type: Date }, 
                  user:       {
                                id:   { type: Schema.ObjectId, ref: 'Users' }
                              }
                },
  created_date: { type: Date, default: Date.now }, 
  updated_date: { type: Date, default: Date.now },        
})

我想将数据推送到lines并尝试通过以下更新来实现:

 exports.update = function (req, res) {
    Stories
    .findOne({ _id: req.params.id }, function (err, story) {
            if (err) {
                res.json(200, {
                    success: "false",
                    message: err.message
                })
            } else {    
        story.maxlines = story.maxlines - 1
        story.lines.push ({
            text : req.body.text,
            'user.id' : req.headers.id,
            entered_at : new Date().toISOString()
        })
        story.save(function(err, story) {
              if (err) {
                res.json(200, {
                    success: "false",
                    message: err.message
                })
            } else if (story) {
                res.json({
                    sucess: "true",
                    message: story
                })
            }
        })
        }

    })

 }

我收到一个错误TypeError: Object { user: {} } has no method 'push',不完全确定如何更新行和与行关联的用户

4

1 回答 1

1

因为story.lines不是数组。您可能需要更新 Schema 以通过这种方式将行转换为 Array 类型:

var LineSchema = new Schema({
    text: {
        type: String
    },
    entered_at: {
        type: Date
    },
    user: {
        id: {
            type: Schema.ObjectId,
            ref: 'Users'
        }
    }
});

var StorySchema = new Schema({
    title: {
        type: String,
        required: true
    },
    users: {
        id: {
            type: Schema.ObjectId,
            ref: 'Users'
        },
        creator: {
            type: Boolean
        }
    },
    maxlines: {
        type: Number,
        default: '10'
    },
    lines: [LineSchema],
    created_date: {
        type: Date,
        default: Date.now
    },
    updated_date: {
        type: Date,
        default: Date.now
    },
})
于 2013-08-03T00:13:50.977 回答