我正在创建一个动物数据库。对于我存储在我的数据库信息中的每个产品,如下所示::
{
"_id": ObjectId("55489125dadf65e30969d6d3"),
"codAnimal": "100001",
"animalData": {
"EN": {
"name": "Monkey",
"description": "The monkey lives in the jungle"
}
}
}
然后我想在同一个动物中添加额外的信息,但是在另一种语言中,使用标签,我想为每种语言添加这样的内容:
"ES": {
"name": "Mono",
"description": "El mono vive en la selva"
}
结果应该是这样的:
{
"_id": ObjectId("55489125dadf65e30969d6d3"),
"codAnimal": "100001",
"animalData": {
"EN": {
"name": "Monkey",
"description": "The monkey lives in the jungle"
},
"ES": {
"name": "Mono",
"description": "El mono vive en la selva"
}
}
}
但我不知道我能用这种方式做什么,而且我不知道这是否可行。我正在使用RESTfull API Nodo.js和Angularjs。
答案 0 :(得分:0)
var query = {
"_id": ObjectId("55489125dadf65e30969d6d3"),
"codAnimal": "100001"
},
update = {
"$set": {
"animalData.ES": {
"name": "Mono",
"description": "El mono vive en la selva"
}
}
};
db.collection.update(query, update, {"upsert": true});
- 更新 - (未经测试)
要通过RESTful API发送此数据,您可能需要考虑更改文档架构,以便使animalData信息成为一个更易于查询的嵌入式子文档,即
{
"_id": ObjectId("55489125dadf65e30969d6d3"),
"codAnimal": "100001",
"animalData": [
{
"language_id": "EN",
"name": "Monkey",
"description": "The monkey lives in the jungle"
},
{
"language_id": "ES",
"name": "Mono",
"description": "El mono vive en la selva"
}
]
}
您的server.js文件应该基本上具有这种设置,您需要使用Mongoose定义数据库模式。模式只是MongoDB中数据的表示。您可以在此处强制将某个字段强制为特定类型。字段也可以是唯一的,仅包含某些字符:
// server.js
var express = require("express"),
mongoose = require("mongoose"),
_ = require('lodash');
mongoose.connect('mongodb://localhost/test') // This connects to a MongoDB db called test
var animalSchema = {
"codAnimal": String,
"animalData": [{
"language_id": String,
"name": String,
"description": String
}]
}
var Animal = mongoose.model('Animal', animalSchema, 'animal')
var app = express();
/**
* Update animal details
*/
app.put('/api/animals/:id', function (req, res){
var animal = req.animal;
animal = _.extend(animal, req.body);
animal.update({ _id: animal.id },
{
"$addToSet": {
"animalData": {
"language_id": req.body.lang,
"name": req.body.name,
"description": req.body.description
}
}
},
function(err) {
if (err) {
return res.send(400, {
message: getErrorMessage(err)
});
} else {
res.jsonp(animal);
}
});
});
app.listen(3000);
以上只是API放置操作看起来如何的一般准系统结构。网上有很多教程提供有关设置MEAN堆栈应用程序的深入代码,您可以查看 First API with Node.js, Express and MongoDB , Create a TV Show Tracker using AngularJS, Node.js and MongoDB < / strong>, Write a todo list with Express and MongoDB 和 MEAN.JS - Full-Stack JavaScript Using MongoDB, Express, AngularJS, and Node.js