首页 > 解决方案 > 不是有效的收集选项,mongodb

问题描述

我正在尝试在 MongoDB 中创建一个集合,但出现错误:

“名称”字段不是有效的集合选项

我正在使用 MongoDB 版本 4.0.0。编码:

const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/newApp', (err, db) =>{
    if (err) {
        return console.log('mongodb connection error'); 
    }

     db.createCollection('people', {
        name: 'sarah',
        age: 27,
        location: 'honolului',
        relationship: 'unknown'
    }, (err, result) => {
            if (err) {
                return console.log('query has not successed retry error code ' + err);
            }

            conole.log(result.ops);
    });
});

标签: javascriptnode.jsmongodb

解决方案


您以错误的方式使用它,您必须像这样使用它:

如需更多帮助:

https://docs.mongodb.com/manual/reference/method/db.createCollection/

db.createCollection( "people", {
       validator: { $jsonSchema: {
          bsonType: "object",
          required: [ "phone" ],
          properties: {
             name: {
                bsonType: "string",
                description: "must be a string and is required"
             },
             age: {
                bsonType : "number",
                description: "must be a number and match the regular expression pattern"
             },
             location: {
                 bsonType: "string",
                description: "must be a string"
             },
             relationship: {
                bsonType: "string",
                description: "can only be one of the enum values"
             }
          }
       } }
    } )

注意:验证器将为您提供应用自定义验证方法的选项,例如requiredunique


推荐阅读