如何在不定义架构的情况下更新集合

时间:2015-06-22 07:52:09

标签: node.js mongodb database

我要在我的数据库中更新一个集合。我不想像在MongoDB中那样定义模式并想要引用现有的集合。有没有办法做同样的事情?

3 个答案:

答案 0 :(得分:0)

您无需定义架构

更新示例,取自node.js MongoDB驱动程序文档:https://github.com/mongodb/node-mongodb-native/blob/master/Readme.md

 var MongoClient = require('mongodb').MongoClient;

  MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
    if(err) throw err;

    db.collection('user').update({_id: '507f191e810c19729de860ea'}, {$set: {firstName: 'John'}}, {w:1}, function(err) {
      if (err) console.warn(err.message);
      else console.log('successfully updated');
    });
  });

这将在user集合中找到文档,其中_id为507f191e810c19729de860ea,并将其firstName属性设置为'John'

答案 1 :(得分:0)

MongoDB是一个无模式数据库,您的集合没有任何预定义模式。

只需执行常规插入或更新,并向文档添加新字段。

答案 2 :(得分:0)

我实际上是想使用mongoose更新集合。因此想出了如何在不定义架构的情况下更新它。 模式需要传递为空白,另一个参数strict应该传递为false。

var schema = new mongoose.Schema({ }, {strict : false});