nihirus nihirus - 1 month ago 4
Javascript Question

Using "@" in key when inserting to MongoDB with mongoose

Mongoose schema won't let me use @ sign in key when inserting to MongoDB with using Node.js. For instance:

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


}, {strict: false});


I tried key with unicode characters like this one:

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


Also tried with normal way using this link(first way), still cannot define key with @:
http://blog.modulus.io/mongodb-tutorial

My purpose is to create document with using JSON-LD format which requires of using @ symbol in key. How to accomplish this? Here are the similar links I have looked for solution:

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

Answer

You can use directly @ between quotes such as "@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();
});
Comments