【发布时间】:2015-03-17 23:27:35
【问题描述】:
我正在尝试设置一个简单的猫鼬测试文件,并且得到了一些非常令人困惑的结果。当我运行以下代码时:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/myapp');
var personSchema = Schema({
name : String,
age : Number,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
var storySchema = Schema({
creator : { type: Schema.Types.ObjectId, ref: 'Person' },
title : String,
fans : [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
var Story = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);
var aaron = new Person({name: 'Aaron', age: 100 });
aaron.save(function (err) {
if (err) console.log("something didnt work!");
var story1 = new Story({
title: "Once upon a timex.",
creator: aaron._id // assign the _id from the person to creator
});
console.log(aaron._id);
story1.save();
});
Story.findOne({ title: 'Once upon a timex.' },function(err,story){
console.log(story); // printing here
});
我得到这个输出:
{
_id: 54b9e08ed983b41d432473e4,
title: 'Once upon a timex.',
_creator: 0,
__v: 0,
fans: []
}
54bcacb4c812ec812382b6b2
这里面有很多没有真正意义的东西。从我的代码中可以看出,我只有 console.log();两件事:
- arron._id
- 在 aaron 的保存回调中创建的故事文档
问题 1: 当我们打印出故事对象时,我们看到 creator 字段设置为 0(我们稍后会谈到),并且由于某种原因添加了下划线(我假设是因为它链接到 ObjectId)。我还尝试向创建者添加下划线,就像它在文档中显示的那样,这导致创建者属性根本无法保存到文档中。谁能解释 _ 如何与猫鼬互动?
问题 2: 当我们尝试将 creator:aaron_id 设置为 0 时,我们知道 arron._id 不是 0,因为我们在同一范围内成功打印了它。我做错了什么?
【问题讨论】: