【问题标题】:Using "@" in key when inserting to MongoDB with mongoose使用 mongoose 插入 MongoDB 时在键中使用“@”
【发布时间】:2017-03-12 08:01:04
【问题描述】:

在使用 Node.js 插入 MongoDB 时,Mongoose 架构不允许我使用 @ 登录键。例如:

var blogSchema = new Schema({
@context : Object //error illegal token
@id : String // illegal token


}, {strict: false});

我试过这样的 unicode 字符键:

"\u0040context" = Object // ignored unicode, inserted as context
 "\x40context" = Object // ignored unicode, inserted as context
 \x40context = Object // illegal token

也尝试使用此链接以正常方式(第一种方式),仍然无法使用@定义键: http://blog.modulus.io/mongodb-tutorial

我的目的是使用 JSON-LD 格式创建文档,该格式需要在键中使用 @ 符号。如何做到这一点?以下是我寻找解决方案的类似链接:
variable with mongodb dotnotation
Syntax error Unexpected token ILLEGAL Mongo Console
How to use mongoose model schema with dynamic keys?
How to do a query using dot( . ) through Mongoose in Node.js and How to add an empty array
Create a Schema object in Mongoose/Handlebars with custom keys/values
http://mongoosejs.com/docs/schematypes.html

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    可以在"@field"等引号之间直接使用@

    "use strict";
    
    var mongoose = require('./node_modules/mongoose');
    
    var Schema = mongoose.Schema;
    var db = mongoose.connection;
    
    var itemSchema = new Schema({
        "@field": {
            type: String,
            required: true
        },
        "@field2": {
            type: String,
            required: true
        }
    });
    var Items = mongoose.model('Items', itemSchema);
    
    var db = mongoose.connect('localhost', 'testDB');
    
    Items.create({ "@field": "value", "@field2": "value" }, function(err, doc) {
        console.log("created");
        if (err)
            console.log(err);
        else {
            console.log(doc);
        }
        db.disconnect();
    });
    

    【讨论】:

    • 哦,感谢您的时间和详细的回答,就像一个魅力。
    猜你喜欢
    • 2016-09-19
    • 2017-12-22
    • 2016-01-21
    • 2014-10-06
    • 2018-05-14
    • 2012-02-07
    • 2019-01-11
    • 2015-09-20
    • 1970-01-01
    相关资源
    最近更新 更多