如何在MongoDB中添加一些对象到一个数组?

时间:2015-08-04 16:27:16

标签: javascript angularjs mongodb express

我在[{1}},angularexpressmongodb中有一个应用程序。

这是我的架构:

nodejs

在这部分我将数据保存到Mongo数据库:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var FirstSchema = new Schema({
    creator: {type: Schema.Types.ObjectId, ref: 'User'},
    object1: String,
    object2: String
});
module.exports = mongoose.model('First', FirstSchema);

如果我有一个文本输入,我如何在里面添加一些.post('/addfirst', function(req, res){ var first = new First({ creator: req.decoded.id, object1: req.body.object1, object2: req.body.object2 }); first.save(function(err, newFirst){ if(err){ res.send(err); return; } io.emit('first', newFirst); res.json({message: "New first Created!"}); }); }) ?像这样:objest1

1 个答案:

答案 0 :(得分:0)

您应将object1定义为Array类型:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var FirstSchema = new Schema({
    creator: {type: Schema.Types.ObjectId, ref: 'User'},
    object1: Array,
    object2: String
});

并按以下方式创建您的实例:

var first = new First({
   creator: req.decoded.id,
   object1: [{<object1_1>},{<object1_2>},{<object1_3>},{<object1_4>}],
   object2: req.body.object2
});