如何将新文件插入mongodb?

时间:2016-10-12 19:02:04

标签: node.js mongodb mongoose

我现在已经创建了架构我想将新文档保存到集合中,但它不会发生在下面的代码中,我是mongodb的新手,任何帮助将不胜感激。

routes.js

var diagram = require('./diagram.model');
var mongoose = require('mongoose');

var Diagram = {

    update: function(req, res) {
        diagram.update({
            _id: req._id
        }, {
            $set: {
                'string': req.string
            }
        }, function(err, result) {
            if (err) {
                return res.status(500).send(err);
            } else {
                console.log("successfully updated document");
            }
        });


    },
    save: function(req, res) {
        var newDiagram = new diagram();
        newDiagram.save(req.body);
    }
}
module.exports = Diagram;

diagram.js

var DiagramSchema = new mongoose.Schema({
  text: String,
  owner: {type: String, ref:'User'},
  groups: [{type: String, ref: 'Group'}],
  users: [{type: String, ref: 'User'}],
  string: String
});
 module.exports=mongoose.model('Diagram', DiagramSchema);

model.js

{{1}}

1 个答案:

答案 0 :(得分:0)

你在保存功能上做错了,save功能应该像

save: function(req, res) {
    var newDiagram = new diagram(req.body);
    newDiagram.save();
}

并确保req.body仅包含string和/或text字段。您可以添加以下检查

save: function(req, res) {
    var diagramData = {
        string: req.body.string,
        text: req.body.text
    }
    var newDiagram = new diagram(diagramData);
    newDiagram.save();
}