当使用Node.js插入MongoDB时,Mongoose模式不允许我使用@ sign in键。例如:
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
答案 0 :(得分:2)
您可以在引号之间直接使用@
,例如"@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();
});