使用nodejs将多个值插入mongodb中的属性

时间:2013-01-02 06:02:48

标签: node.js mongodb mongoose

您好我使用以下代码将值插入我的mongodb

var mongoose = require('mongoose');
var db = mongoose.createConnection('mongodb://localhost/TruJuncSVC1');
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {

console.log('connection opened in Mongodb with SAMPLE TESTING Database')
var schema = new mongoose.Schema({Response: String,Id:String,Name:String,News:String,Details:String});

var SvcOrch = db.model('SvcOrch', schema);
var data = new SvcOrch({ 'Response': 'DailyLoad','Id':'S3000981','Name':'Stears','News':'Mens Boutiques Try New Tactics for Winning Loyal CustomersTradition Finds New Biz in Old Font','Details':'Stears Roebuck and Co. or Stears, is an American chain of department stores,[2] which was founded by Richard Warren Sears and Alvah Curtis Roebuck in the late 19th century. Formerly a component of the Dow Jones Industrial Average, Stears bought out Kmart[3] in early 2005, creating the Stears Holdings Corporation.'});


                        data.save(function (err) {
                        if (err) return handleError(err);
                        // saved!
                        console.log('\nResponse data saved in MongoDB')
                        })
                        });
                        });

我能够为每个属性插入一个值,我需要为单个属性保存多个值,说id应该具有2或3个值,所有属性都是相同的。任何想法如何进一步继续将是很多有用。谢谢提前

2 个答案:

答案 0 :(得分:0)

如果需要为单个属性存储多个值,请将其声明为数组。

例如,如果您希望为每个文档存储多个news项,则需要将架构更改为:

var schema = new mongoose.Schema({
    Response: String,
    Id: String,
    Name: String,
    News: [String],
    Details: String
});

创建包含多个新闻值的新项目:

var data = new SvcOrch({
    Response: 'DailyLoad',
    Id: 'S3000981',
    Name: 'Stears',
    News: ['News item 1', 'News item 2'],
    Details: 'More details...'
});

答案 1 :(得分:0)

windowWillClose

即使我们不更改架构,多值字段也会自动输入到mongodb中。系统会根据数据自动重新定义。上面的代码是一个示例node.js代码,可以使用post方法将数据输入到mongodb