我正在尝试设置一个容纳房间对象的mongodb。任何人都可以看到为什么只有垃圾被添加到我的数据库?我的房间对象有5个房间,所以正在添加正确数量的东西,它们只是没有正确添加。
这就是我设置db的方式:
var setupRoomDB = function(){
var roomSchema = mongoose.Schema({
title: String,
description: String,
exitList: [String]
});
Room = mongoose.model("Room", roomSchema);
addRoomsJS();
}
db.once('open', setupRoomDB);
这很有效。现在我想用我在这个对象中包含的东西填充我的数据库:
var rooms = {
bridge: {
title: "Bridge",
description: "You are on the Bridge. There are big comfy chairs and a big screen here.",
roomExits: ['sickbay'],
},
engineering: {
title: "Engineering",
description: "You are in Engineering. There are lots of funny instruments, many smaller screens, and kind of uncomfortable chairs.",
roomExits: ['sickbay'],
},
etc
这就是我尝试这样做的方式:
var addRoomsJS = function (){
for (var room in rooms){
var addRoom = function (err, rooms){
//if the room is already contained
if (rooms.length!=0){
//res.redirect("/?error=room already exists");
return;
}
var newRoom = new Room({
title:room.title,
description : room.description,
roomExits: room.roomExits
});
newRoom.save();
};
Room.find({title:room.title}, addRoom);
}
}
当我查看我的数据库中存储的内容时,这就是我得到的内容:
sarah@superawesome:~/comp2406/adventure-ajax-demo$ mongo
MongoDB shell version: 2.4.6
connecting to: test
> show dbs
local 0.078125GB
test (empty)
users 0.203125GB
> use users
switched to db users
> show collections
rooms
system.indexes
> db.rooms.find()
{ "_id" : ObjectId("529cd5686f854f1512000001"), "exitList" : [ ], "__v" : 0 }
{ "_id" : ObjectId("529cd5686f854f1512000002"), "exitList" : [ ], "__v" : 0 }
{ "_id" : ObjectId("529cd5686f854f1512000003"), "exitList" : [ ], "__v" : 0 }
{ "_id" : ObjectId("529cd5686f854f1512000004"), "exitList" : [ ], "__v" : 0 }
{ "_id" : ObjectId("529cd5686f854f1512000005"), "exitList" : [ ], "__v" : 0 }
答案 0 :(得分:3)
exitList
的schmea更改了该属性的名称。然而,当你创建房间时,它被称为roomExits
。rooms
对象中抓取实际对象。 __v
是猫鼬versionKey
(Reference和how to disable)使用for(var x in obj)
时,x
是密钥的名称,但不是值。因此,在您的示例中,它只是bridge
作为字符串。您需要从rooms
对象中获取实际对象:
var r=rooms[room];
你可以用一个闭包来包装循环的内容并获取值:
for (var room in rooms) {
(function(room) {
var addRoom = ... /* your code here */
})(rooms[room]);
}
如果你不使用闭包,那么当异步find
函数返回时,room
的值不仅仅是一个字符串,它将是 last < / strong>关联数组中的值(无论in
处理的最后一个属性是什么)。
答案 1 :(得分:0)
我不知道你对垃圾的意思,但是:
__v
字段由Mongoose创建,如果您尝试从2个不同的进程编辑数组,则用于检查。